![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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! } }
Advertisements