TITLE: loop testing for IO (Newsgroups: comp.lang.c++.moderated, 1 Jun 97) BELLINGHAM: Alan Bellingham > > > What's wrong with: > > for(;;) > { > in >> object ; > if ( in.eof()) > break ; > out << object; > } CLAMAGE: Steve Clamage If eof() is true, it doesn't mean the previous input failed. If eof() is false, it doesn't mean the previous input succeeded. Your example illustrates why you normally do not want to use eof() for loop control. If input failed due to incorrect format, the loop outputs that last successful input forever, never reading more, and never terminating. But if eof was set as as result of reading the last value, you don't output the last value. The only safe assumption about eof() is when it returns true, it means no more input data is available. You could rewrite the above loop like this for(;;) { // repeat input until failure in >> object; if( ! in ) break; // previous input failed out << object; } // find out what caused the failure if( in.eof() ) ... we processed all the input else ... last input failed but not because of eof I would probably write the loop like this do { in >> object; if( in ) out << object; } while( in ); I find this style of coding easier to understand and maintain -- it says exactly what it means, and its obvious where to put additional code that depends on whether the input succeeded. (Yes, it repeats a test, but I doubt you could measure the difference in performance since the test is really cheap, and I/O is really expensive.)