The following C++ code uses a ifstream object to read integers from a text file (which has one number per line) until it hits EOF. Why does it read the integer on the last line twice? How to fix this?
Code:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
    ifstream iFile("input.txt");    // input.txt has integers, one per line
    while (!iFile.eof())
    {
        int x;
        iFile >> x;
        cerr << x << endl;
    }
    return 0;
}
input.txt:
10  
20  
30
Output:
10  
20  
30  
30
Note: I've skipped all error checking code to keep the code snippet small. The above behaviour is seen on Windows (Visual C++), cygwin (gcc) and Linux (gcc).
 
     
     
     
     
     
     
    