Do not read, not eof() 1 . This is not a valid read cycle.
Reading while reading is successful .
int x; while ((x = in.get()) != EOF) { cout << x << endl; }
Testing in.eof() does not guarantee that reading will succeed. When you test in.eof() , you are actually checking if previous reads were trying to read the end of the file. This is bad because it means that the previous read operation failed. That failed, and you didn't care, and just clicked to use the return value, even if it didn't work out.
When in.get() fails, it returns an EOF constant. This is what you should check. If in.get() fails, you don't want to continue your loop as if it succeeded.
1 The same applies to while good() or until bad() .
R. Martinho Fernandes
source share