Ctrl+Z causing double entry in while(cin)

Using ctrl+z to exit a while loop causes the loop to record the last value twice into my vector. Any idea why?
1
2
3
4

while(cin)
{ cin>>input
vector.pushback(input)}


but if i use something like this, I do not get the problem

1
2
3

while(cin>>input)
{ vector.pushback(input)}
Last edited on
The first one checks cin, then tries to read the input and then it adds it to the vector no matter if the read was successful or not.

The second one first tries to read the input, then it checks cin, and only if cin is in a good state (meaning the last read operation was successful) it adds it to the vector.
Last edited on
One quirk of C++ is that a stream doesn't register end-of-file until after you try to read past EOF. Put another way, after reading the last character in a stream, the stream is still good, it's only when you try to read one more character that eof() becomes true.

This makes sense if you think of keyboard input. You don't even know you're at the end of the stream until you try to read the next character.
Topic archived. No new replies allowed.