Using eof() function displays numbers twice?

I have a text file with the numbers:
256
314.654

When I run my program it displays:
256
314.654
256
314.654

why is it displaying the numbers twice?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32

#include <iostream>
#include <fstream>
using namespace std;

int main ()
{
    int x;
    float y;

    ifstream newfile;
    newfile.open ("sample.txt");

    if (newfile == 0)
    {
        cout << "error opening sample.txt" << endl;
        return 1;
    }

    while (!newfile.eof())
    {
        newfile >> x;
        newfile >> y;
        cout << x << endl;
        cout << y << endl;
    }
    
    newfile.close ();

return 0;
}

eof does not get set until you are at eof AND you have attempted to read something. Don't loop on eof, instead loop on the stream itself:

while(newfile)
Because eof is only set when you try to read beyond the end of file - which means you
are in the middle of the loop when this happens, which means
1
2
 newfile >> x;
  newfile >> y;
fails, which means x and y don't change from their previous values, and
1
2
cout << x << endl;
cout << y << endl;
will display the previous values. Then you go back to the top of the loop and the eof test fails - but it is too late then.

This repeat-of-last-value-in-file is a problem when you loop on eof like you have done.

It also has another problem, in that if the file is bad or problems reading values - you can get an infinite loop situation.
Last edited on
Topic archived. No new replies allowed.