Avoid Loop Control Using eof()
All over the 'net C++ programmers are taught to "read until end of file". This leads to the following (incorrect) idiom for loop control.
#include <iostream>
#include <fstream>
int main()
{
std::ifstream file("file.txt");
if ( file )
{
int i;
while ( !file.eof() ) // bad!!
{
file >> i;
std::cout << i << ' ';
}
std::cout << std:: endl;
}
return 0;
} Run the above code with the following text file, "file.txt".
Your output will be like this.
Note the repeated 10.
What To Use Instead
Change your thinking to "while successfully reading input from a file" and know that the state of the stream -- indicating successful input or a failure -- is available from the input operation.
#include <iostream>
#include <fstream>
int main()
{
std::ifstream file("file.txt");
if ( file )
{
int i;
while ( file >> i )
{
std::cout << i << ' ';
}
std::cout << std:: endl;
}
return 0;
} The output is now correct.
Then, for amusement, change "file.txt" to this.
Then run each of the above programs.
Another Example
A similar thing can be done when reading text.
#include <iostream>
#include <fstream>
int main()
{
std::ifstream file("file.txt");
if ( file )
{
char line[80];
while ( file.getline(line, sizeof line) )
{
std::cout << line << '\n';
}
}
return 0;
} Copy this source into "file.txt" and it will print out this code.
Further Reading:
http://www.parashift.com/c++-faq-lit....html#faq-15.2
http://www.parashift.com/c++-faq-lit....html#faq-15.3
http://www.parashift.com/c++-faq-lit....html#faq-15.4
http://www.parashift.com/c++-faq-lit....html#faq-15.5