
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
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 Articles
- Why the use of iostream::eof inside a loop condition considered wrong?
- Why is Petrol considered a mixture?
- Why Dante is considered a great poet?
- Why is LPG considered a good fuel?
- Why is air considered as a mixture?
- (a) Why is it wrong to treat a bee sting with vinegar?(b) Why is it wrong to treat a wasp sting with baking soda solution?
- Why is Pablo Picasso considered a great artist?
- Why is JavaScript considered a loosely-typed language
- Why is biogas considered excellent fuel?
- Why crop rotation is considered a good agricultural practice?
- A caterpillar is considered to be an insect. Why?
- Why is LPG considered a better fuel than coal?
- Apply a condition inside subset in MongoDB Aggregation?
- Why is air considered a mixture and not a compound?
- Why is river Ganga considered as sacred?

Advertisements