1

I have a file containing only one character 1 (there is no newline symbol after it)

Reading the contents with this method:

int value;
ifstream in("somefile");
for (!in.eof())
{
    in >> value;
    cout << "input: " << value << " , eof" << in.eof() << "'\n";
}

gives me the following output:

input: 1 , eof: 0
input: 1 , eof: 1

The questions are:

1) Why EOF flag is not set after first reading try? I mean, if program successfully reads the number on the first try, it somehow knows that the string representatiion of it is over. To find it out it has to try read at least one byte after 1 character and there it should have hitted EOF. Why that doesn' happen?

2) That said, if I have a file with one value per line, I always do have a duplicate of last input. Does it mean that I always have to discard it in any way and that would be correct? Or for example add extra check for EOF after in >> value; and only if it succeeds, do any logic I want?

I know that I can work around with readline() or while(in >> value) methods but it's more a question of understanding what really happens there.

Thank you.

DimG
  • 1,434
  • 1
  • 12
  • 19

0 Answers0