Why the use of iostream::eof inside a loop condition considered wrong?



Just because we haven't reached the EOF, doesn't mean the next read will succeed.

Consider you have a file that you read using file streams in C++. When writing a loop to read the file, if you are checking for stream.eof(), you're basically checking if the file has already reached eof. 

So you'd write the code like −

Example

#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       }    } }

Example

While when you use the stream directly in a loop, you'd not be checking the condition twice −

#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!    } }
Updated on: 2020-06-23T13:40:06+05:30

204 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements