Why is iostream::eof inside a loop condition considered wrong?

C++Server Side ProgrammingProgramming

The iostream::eof in a loop is considered as wrong because we haven’t reached the EOF. So it does not mean that the next read will succeed.

When we want to read a file using file streams in C++. And when we use a loop to write in a file, if we check the end of file using stream.eof(), we are actually checking whether the file has reached end or not.

Example Code

#include<iostream>
#include<fstream>
using namespace std;
int main() {
   ifstream myFile("myfile.txt");
   string x;
   while(!myFile.eof()) {
      myFile >> x;
     // Need to check again if x is valid or eof
     if(x) {
        // Do something with x
     }
   }
}

When we are using the stream directly in a loop, We will not check the condition again.

Example Code

#include<iostream>
#include<fstream>
using namespace std;
int main() {
   ifstream myFile("myfile.txt");
   string x;
   while(myFile >> x) {
      // Do something with x
      // No checks needed!
   }
}
raja
Published on 15-Mar-2019 11:23:14
Advertisements