while (cin >> Ch)
{ // we get in here if, and only if, the >> was successful
if ((Ch == '\n') || (Ch == ' '))
{
++WordCount;
LetterCount = 0;
}
else
++LetterCount;
}
That's the safe, and common, way to rewrite your code safely and with minimal changes.
(Your code is unusual, trying to scan all characters and count whitespace and newlines. I'll give a more general answer to a slightly different question - how to read in all the words.)
The safest way to check if a stream is finished if if(stream)
. Beware of if(stream.good())
- it doesn't always work as expected and will sometimes quit too early. The last >>
into a char
will not take us to EOF, but the last >>
into an int
or string
will take us to EOF. This inconsistency can be confusing. Therefore, it is not correct to use good()
, or any other test that tests EOF.
string word;
while(cin >> word) {
++word_count;
}
There is an important difference between if(cin)
and if(cin.good())
. The former is the operator bool
conversion. Usually, in this context, you want to test:
"did the last extraction operation succeed or fail?"
This is not the same as:
"are we now at EOF?"
After the last word has been read by cin >> word
, the string is at EOF. But the word
is still valid and contains the last word.
TLDR: The eof
bit is not important. The bad
bit is. This tells us that the last extraction was a failure.