I am struggling a bit with understand the file input stream in C++. I have a code snippet as follows:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
ifstream in("x.txt");
bool done = false;
do {
string input = "";
getline(in,input);
int x1;
int x2;
in >> x1;
in >> x2;
cout << input << " " << x1 << " " << x2 << endl;
in.ignore();
if(in.eof()) {
done = true;
cout << "reached eof" << endl;
}
} while(!done);
return 0;
}
With the file x.txt reading as follows
task1
12
1313
task2
13
1414
[blank line]
Note the intentional inclusion of the blank line at the end of the input file. All this means is that the enter/return key was pressed after typing '1414'.
My expected output is
task1 12 1313
task2 13 1414
reached eof
But in actuality, the output is
task1 12 1313
task2 13 1414
13 1414
reached eof
I understand that pressing enter within an input file generates an implicit newline character, and before using a statement like getline(ifstream, string)
we should ignore()
that next newline character. With that being said, why is ifstream.eof() not evaluating to true even though I ignore()
the implicit newline character after '1414'?