In Bjarne Stroustrup's Programming Principles and Practice Using C++ (Sixth Printing, November 2012), if (cin)
and if (!cin)
are introduced on p.148 and used in earnest on p.178. while (cin)
is introduced on p.183 and used in earnest on p.201.
However, I feel I don't fully understand how these constructs work, so I'm exploring them.
If I compile and run this:
int main()
{
int i = 0 ;
while (cin) {
cout << "> ";
cin >> i ;
cout << i << '\n';
}
}
I get something like:
$ ./spike_001
> 42
42
> foo
0
$
- Why is it that entering "foo" apparently causes
i
to be set to0
? - Why is it that entering "foo" causes
cin
to be set tofalse
?
Alternatively, if I run and compile this:
int main()
{
int i = 0 ;
while (true) {
cout << "> ";
cin >> i ;
cout << i << '\n';
}
}
I get something like:
$ ./spike_001
> 42
42
> foo
> 0
> 0
...
The last part of user input here is foo
. After that is entered, the line > 0
is printed to stdout repeatedly by the program, until it is stopped with Ctrl+C.
- Again, why is it that entering "foo" apparently causes
i
to be set to0
? - Why is it that the user is not prompted for a new value for
i
on the next iteration of the while loop afterfoo
was entered?
This is using g++ (Ubuntu/Linaro 4.6.3-1ubuntu5) 4.6.3
.
I'm sorry for such a long question, but I think it all boils down to, "How is cin evaluated?"