It is commonly advised that using the EOF flag for file input is erroneous in C++. The follwoing article explains why:
EOF And Reading Text Files (C++) - C++ Tutorials | Dream.In.Code
I especially don't get the paragraph:
In lamens terms, why, using EOF, does the last entry or character get repeated twice?Uh oh! First the program tells you that its read 6 names when there are only 5 names in the file, and then it goes on to display the last name twice.
What has happened is that the while loop has been repeated 6 times, because it is repeating until namefile has its internal "EOF" flag set. Remember that ifstream is not a file, its a stream, which means that it cannot know whether or not there is any more data in a file until after a failed attempt to read past the end of the file. After it read "Harry" from the file, the stream had not failed, therefore the EOF flag was still unset.
There's an even worse (more subtle) problem with this, based on how the >> operator works; it will always stop reading at the first 'whitespace' character it encounters - a space, a newline, a carriage return or a tab.