user3064097
user3064097

Reputation: 161

Code is failing to run properly after trying to read input from file

I have an input file set up like this:

Hello there
1 4
Goodbye now
4.9 3

And I try to read the data as so:

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main(){
    ifstream input("file.txt");
    string name;
    double num1, num2;

    while(!input.eof()){
        getline(input, name);
        input >> num1;
        input >> num2;

        cout << name << endl;
        cout << num1 << " " << num2 << endl;
    }
}

But the read seems to be failing. Can anyone help me here?

Upvotes: 3

Views: 73

Answers (2)

Abhishek Bagchi
Abhishek Bagchi

Reputation: 21

This would work..

ifstream input("command2");
string name;
double num1, num2;

int x;

while(getline(input, name)){
    input >> num1;
    input >> num2;
    input.clear();
    cout << name << endl;
    cout << num1 << " " << num2 << endl;
    string dummy;
    getline(input,dummy);
}

I write the second getline() to make sure that the \n at the line with 1 4 is read.

Without that, what i get is

Hello there
1 4

0 4
Goodbye now
4.9 3

Hope this helps.

Upvotes: 0

gongzhitaao
gongzhitaao

Reputation: 6682

Problem 1: getline with >>. Solution from this post: C++ iostream: Using cin >> var and getline(cin, var) input errors

Problem 2: inupt.eof() to test the end of loop, this post: Why is iostream::eof inside a loop condition considered wrong?

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main(){
  ifstream input("dat.txt");
  string name;
  double num1, num2;

  while (getline(input, name)) {  // getline fails at the end of file
    input >> num1 >> num2;
    input.ignore();
    cout << name << endl;
    cout << num1 << " " << num2 << endl;
  }
}

Upvotes: 2

Related Questions