A basic input loop should
work like this:
while (true)
{
try to get input;
if (not successful) break;
do something with the input;
}
|
The extraction operator in C++ makes code that does this very natural looking:
1 2 3 4 5
|
char c;
while (cin >> c)
{
...
}
|
This works because the result of
cin >> c
is the
istream object itself, which is then tested for a boolean value, which the
istream overloads to mean "is
good()?". If the stream is not
good() (because of an input error or EOF), then the loop quits.
Another way to do it is:
1 2 3 4 5
|
int c;
while (cin.get( c ))
{
...
}
|
Again, the loop condition is really doing two things: attempting to get a single character from the stream and returning the
istream object, which is then tested for
good()ness. Had anything gone wrong when attempting input, the stream is not
good() and the loop terminates immediately.
EOF is short for "end of file", which is just a way of saying that there isn't any more input to be read.
For example, given the string "abc", if we get one character at a time from it we get 'a', then 'b', then 'c', then... then there are no more characters. We've hit the end of the string. That's exactly what is happening at EOF -- end of file.
BTW, the two code fragments above are not quite equivalent. The
>>
operator skips leading whitespace, while
cin.get() does not. You can make them work equivalently by turning on the "no skip whitespace" flag:
1 2 3 4 5 6
|
cin >> noskipws;
char c;
while (cin >> c)
{
...
}
|
There are still minor differences between them, but not that you can see if you were to use it this way.
Hope this helps.