View Single Post
Aug 23rd, 2005
0

Re: C and C++ Timesaving Tips

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".
Quote ...
1 2 3 4 5 6 7 8 9 10
Your output will be like this.
Quote ...
1 2 3 4 5 6 7 8 9 10 10
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.
Quote ...
1 2 3 4 5 6 7 8 9 10
Then, for amusement, change "file.txt" to this.
Quote ...
1 2 3 4 5 6 7 8 9 1A
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
Team Colleague
Reputation Points: 2780
Solved Threads: 312
long time no c
Dave Sinkula is offline Offline
4,790 posts
since Apr 2004