Something is amiss in the documentation of
int istream::get():
http://www.cplusplus.com/reference/iostream/istream/get/.
The information is consistent with other sources, but it is written that "the function returns the character read". However, if that was the case, the return type would be
char, not
int. Actually the return type is extended in order to be able to return the special value
EOF which appears to be defined in
<cstdio> (
http://www.cplusplus.com/reference/clibrary/cstdio/EOF/). But EOF is actually the integer -1.
What is important to know though, is that the error flags and the
end-of-file flag are set after the fact. For example, suppose you read the last character, therefore reaching the end of the file. But the end-of-file indicator will not be set. You try to read again, the IO function you called fails miserably (but in well defined, officially documented way, I mean), and now the end-of-file indicator is raised.
So you can not check if the file can be read further before the IO operation, like at the beginning of the loop. You have to check after the IO operation. You can use the strategy:
1 2 3 4
|
while (cin >> ch)
{
...
}
|
or the strategy:
1 2 3 4
|
while ( (ch= cin.get() ) != EOF )
{
...
}
|
, but I wander, is the latter not documented officially for a reason.