Gernot Frisch wrote:
ifstream is("filename.txt"); // open a file stream
string line; // S string for a line to read
while(is.good()) // As long as there's data
{
is >> line; // read a line
cout << line << endl; // output it
}
Not a good idea. The typical question with code like this
is: "Why is the last word processed twice?"
A stream goes into a fail state (such as eof) only until
you try AND fail to read past the end of file. Thus the
above loop will have undefined behaviour when is >> line
fails the first time (usually at eof). The read operation
fails and yet you process it as if nothing has happened.
So at least it has to read
while( is.good() )
{
is >> line;
if( is.good() )
cout << line << endl;
}
The usual idiom in C++ is
while( data can be read ) {
do something with the read data
}
if( stream is not in eof state )
there was an error during read
else
all data could be read correctly
------
while( is >> line ) {
cout << line << endl;
}
if( !is.eof() ) {
cout << "There was an error during read\n";
return;
}
--
Karl Heinz Buchegger
kb******@gascad.at