

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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 is iostream::eof inside a loop condition considered wrong?
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! } }
- Related Questions & Answers
- Why the use of iostream::eof inside a loop condition considered wrong?
- Why Dante is considered a great poet?
- Why is Pablo Picasso considered a great artist?
- Why Lord Krishna is considered supreme god?
- Why is river Ganga considered as sacred?
- Why Anger is considered as self-killer/destroyer?
- Why is Tulsi plant considered sacred in Hinduism?
- Why is Steve Jobs considered as a role model for leaders?
- Why is Wealth Maximization considered superior to Profit Maximization?
- Why are women considered bad drivers?
- Why is Swami Vivekananda considered an inspirational leader even today?
- Why Rainy season is not considered good to start exercising?
- Why do we have a different time zones and why GMT is considered as the standard?
- What is Methanol and why is it considered an alternative cooking fuel?
- Apply a condition inside subset in MongoDB Aggregation?
Advertisements