It is bad idea to test the stream on the outside and then read/write to
it inside the body of the conditional/loop statement. This is because
the act of reading may make the stream bad. It is usually better to do
the read as part of the test.
In the previous example, Why do we need to distinguish eof and fail? When
fail happen, maybe there are invalid character in buffer. After clean the
buffer, I can continue to read input from input buffer. Three methods to
clean invalid character in the buffer
In summary, It’s better just use judgment to exit end loop. If youneed to different specific action to take to deal with EOFor error. Use while(true), then use eof() of feof() fail() orclear() functions in c++ and c to deal with and break theloop;