cin
loopcin
in a while
loop
int sum = 0;
int x;
while (cin >> x) {
sum = sum + x;
}
cout << sum;
cin
in a while loop is a very common
style of programming.
cin
not only reads values into
variables, but it also produces a value. That's because
>> is an operator that produces a value.
This value can be tested in loops and ifs.
cin >> x
is true if
a value was read into x
.
cin >> x
is false if it was unable to read.
There are several possible causes for a reading failure.
Use this pattern when reading. Another style, which is not generally
used is Anti-idiom - Using cin
in three places, instead of one.