Here is a small contrived program which prints the integer just typed to the screen.
#include <iostream>
int main(int argc, char *argv[])
{
int n;
while(std::cin>>n)
{
std::cout<<"You typed "<<n<<std::endl;
}
return 0;
}
Now when I enter integers the program works normally. However, if I enter floating point numbers like 10.8 the program displays 10 to the screen (as it should, since it is casting the floating point number to an integer), and then the program exits. Why is this happening? Given below is a sample terminal output.
Desktop: ./a.out
4
You typed 4
-9
You typed -9
10.8
You typed 10
Desktop:
After “You typed 10” line, the characters “.8” remain in the stream. When it tries to read that into an integer, it fails, and so it puts the stream into a bad state.
Since the stream is in a bad state, your loop condition fails and you fall out of the loop.
(Specifically, it sets the “bad” bit, I think, but it’s been too long since I dealt with that and I’m not sure — check the documentation if you need that level of detail)
Aside: be aware if you tried to read again, the characters “.8” would still remain in the stream, and you would fail again. This is a common I/O error.