2

The code is:

ifstream fin("D://abc.txt", ios::in);
string line;
while ( fin ) {
    getline( fin, line );
    cout << line << endl;
}

The text file is:

hi, I am Eric!
hi, I am Jack!

And the output is

hi, I am Eric!
hi, I am Jack!
hi, I am Jack!

And when I change the condition to !fin.eof(), output is correct. Is eof a valid state of ifstream ?

Joey.Z
  • 4,492
  • 4
  • 38
  • 63

3 Answers3

4

It's because the state is not changed until after the std::getline function fails. This means that you read the first two lines correctly, but then the state isn't changed so you enter the loop again, but now the std::getline call fails but you don't check for it, and it's also now that the eof flag is set.

You should do e.g.

while (std::getline(...))
{
    // ...
}
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
3

The eof state is only reached once you try reading past the end of the stream. The getline call that reads the last line from your file does not do so (it reads up until the newline). But the getline call in the next iteration of the loop will reach the end of the file.

A better way to read every line in the file is :

while (getline(fin, line)) {
    cout << line << endl;
}
Sander De Dycker
  • 16,053
  • 1
  • 35
  • 40
1

The usage

while(fin)

is not good. it will check the value of fin, not whether fin reaches the end.

you may check this page: http://www.cplusplus.com/reference/string/string/getline/

when you finish the second call of function getline, the pointer fin not point to NULL, so you go into the third process in while, the third time you call

getline(fin,line);

it meet the eof of fin, so fin change state, then you won't go to the forth call, but since you didn't clear the value of

line

so it will also print

hi, I am Jack!
Yang
  • 754
  • 2
  • 8
  • 22