Reputation: 7491
I have the following program:
int main() {
int i;
while (cin >> i) {
cout << abs(i) << endl;
}
return 0;
}
(where abs is defined by int abs(int val))
when I input a non-int number, for example, -1.2, it will give the following output:
$ -1.2
1
My question is: why the while body gets executed? I think the condition should fail as soon as I input a non-int value and the program should terminate. Thanks!
Upvotes: 2
Views: 72
Reputation: 762
Your program only reads one integer, not any more than that. If you use cin
to read an int value the operator will only read an int, so using a decimal will make it only read up to the dot. Entering -55.365, for example, would really only send -55.
Upvotes: 2
Reputation: 409166
Because the input operator reads -1
, and stops at the dot. Next time through the loop the input operator sees the dot and sets the fail
flag, terminating the loop.
Upvotes: 2