3

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?

2
  • getline didn't remove the \n from the stream Commented Dec 4, 2013 at 3:12
  • Prefer "\n" to std::endl unless you have a reason to flush. Commented Dec 4, 2013 at 3:18

2 Answers 2

2

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;
  }
}
Sign up to request clarification or add additional context in comments.

2 Comments

The output i get with your code for the file contents mentioned in the question is Hello there \n 1 4 \n 0 4
@AbhishekBagchi Interesting, I got the correct output with gcc 4.8 on Ubuntu 13.10.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.