Search code examples
c++c++11fstream

On comparing different way of reading an integer from a file


While reading this question, I found in the answers different way of reading an integer. Here are two of them.

The one from πάντα ῥεῖ's answer:

if(iFile) {
    iFile >> int1;
    cout << "From first file:" << int1 << endl;
}

The one from JRowan's answer:

if(!iFile.eof()){
    iFile >> int1; 
    cout << "From first file:" << int1 << endl;
}

But I was wondering if using the code below is equivalent to the two above? Also, is there any reason not to use one of the three sample codes?

if (iFile >> int1) {
   cout << "From first file:" << int1 << endl;
}

Thanks.


Solution

  • On constructing the ifstream object iFile, you should check that there were no errors. This is correctly accomplished by simply doing if(iFile) in both C++ and C++11. Assuming you have already done this check, the third code snippet is the only correct way of reading the ints from file. The first two methods will end up printing the last integer before eof twice. This is because they don't check the state of the stream after doing iFile>>int1. So, if they had encountered eof, you wouldn't know and continue to call cout.