I’m a little confused as to what’s going on, i’m playing with some programs from “Accelerated C++”, and have hit a problem with one of the early programs (page 35, if you happen to have a copy nearby).
It uses this snippet:
while (cin >> x) {
++count;
sum += x;
}
(“count” is an integer, “x” is a double)
It works as intended, allowing me to enter several values and add them together, but i can’t work out what’s going wrong with “End-of-file” signalling. The book says the loop will keep running until the program encounters an end of file signal, which is ctrl+z in windows.
This is all fine, and works, but then my program won’t let me use cin again. I usually just set up a program to wait for some random variable in order to stop the console closing immediately after executing (is there a better way to do that, by the way?) which is how i noticed this, and i’m wondering if there’s a solution. I’ve done a bunch of searching, but found little that doesn’t say what’s already said in the book (press ctrl+z, or enter a non-compatible type of input etc.)
I’m using Visual studio 2008 express to compile.
From one point of view, once you’ve hit the end of an input stream then by definition there’s nothing left in the stream so trying to read again from it doesn’t make sense.
However, in the case of ‘end-of-stream’ actually being caused be a special character like Ctrl-Z on windows, we know that there is the possibility that we could read again from
cin. However, the failed read will have caused theeofflag on the stream to be set.To clear this flag (and all the other failure flags) you can use the
clearmethod.After calling this, you can attempt another read.