0

I need some clarification on the eof( ) file stream function in C++. In my textbook, it says "inStream.eof() does not become true until the program attempts to read one character beyond the end of the file." if inStream were an ifstream object. However, when I've been writing a program that reads integers from a file, and let's say my ifstream object was called "fin", then fin.eof() gets set when I read the last integer. Therefore, if I had some mini program that simply read integers from one file and printed them to another file:

ifstream fin("input.txt");
ofstream fout("output.txt");
int num;

fin >> num;
while (!fin.eof()) {
     fout << num << endl;
     fin >> num;
}

and lets say my input file was

9
10
11

Then my output would be

9
10

By debugging I found that for some reason when "fin >> num" reads the last number, it sets the eof flag so the condition in the while loop evaluates as false and it breaks. This is contrary to what my textbook said and I'm just confused. If it's compiler dependent, then I'm using visual studio 2019 so maybe that's the issue. Else, I'm not sure since my textbook is saying one thing and a different thing is happening in my program.

Off the top of my head, the only thing I can think of is my textbook explained eof() in terms of reading characters and right now I'm reading integers from a file so maybe there's a difference.

  • To know that it has read all of the characters of the integer it has to keep reading until it hits a non-digit, which therefore tries to read past the end of the file (depending on file contents obviously). – M.M Jun 11 '20 at 00:30
  • That makes sense. Is there a way around this that's analogous to what happens in C? For example, in C I would just use the return value of fscanf to see if it hit EOF and I didn't have the same problem. fscanf would only return EOF after it read the last number and not when it read the last number. –  Jun 11 '20 at 00:33
  • See this [question](https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-i-e-while-stream-eof-cons). – 1201ProgramAlarm Jun 11 '20 at 00:33
  • Yes, use the return value of `fin >> num`. I.e. `while (fin >> num) fout << num << endl;`. You really want to test whether the read succeeded -- which is not exactly the same as whether EOF was reached – M.M Jun 11 '20 at 00:34
  • BTW in C if using the return value of fscanf, you should test if it equals the number of elements you expected. (testing for != EOF is a common mistake) – M.M Jun 11 '20 at 00:35

0 Answers0