The condition for a loop to break is a statement, whose value must evaluate to boolean value
false
. Now, in C++ almost any statement evaluates to something and that something can be casted to
bool
. The simplified rule is that everything evaluates to
true
, except
0, \0, null
.
For this reason you may create a loop:
1 2
|
while (x) // and not neccessarily while(x > 0)
x--;
|
and it will go x times, because when x = 0, it is casted to
bool
and returns
false
.
Now, you might not have been aware, that
cin
is not a simple keyword of C++ language. It is in fact a function that returns object of class istream:
http://www.cplusplus.com/reference/iostream/cin/ .
Now, consider the
>>
operator. Operator overloading mean anyhing to you yet? When you use
>>
with
cin
you are calling a function explained here:
http://www.cplusplus.com/reference/istream/istream/operator%3E%3E/
(Or more precisely one of these functions, depending on what type is the variable you try to save data to, like
intVar
.) This function is returning something. This something may be casted to
bool
, and the result will be either
true
or
false
.
Now, did you notice, that when you declare a variable of type
int
you cannot
cin
a letter into it? In such event the return value of
operator>>(int)
is a boolean
false
. It would cause the loop to break.
You assumed that
while(cin >> var)
will break if you simply press enter. In fact it would break whenever what user inputs cannot match the
var
's type - and makes the operator function return value that is boolean equivalent of
false
.
So in short - much depends on type of the
var
you
cin
into, and part of your problem may be that
intVar
is not quite a
var
of type
int
.
Notice that these two loops are much different:
1 2 3 4 5 6 7 8 9 10 11 12
|
int intVal;
char charVal;
while(cin >> intVal)
{
cout << intVal; // mirrors your numbers
}
cout << endl << "Now the other loop" << endl;
while (cin >> charVal)
{
cout << charVal; // mirrors single letters of what you type.
// Breaks in different situations than the previous loop
}
|
Look how this would work when you input all digits, digits and letters, multiple letters and so on.