C++ Notes: Idiom - cin loop

Idiom: Read from cin in a while loop

The standard C/C++ style for reading is to put the read operation in a while loop condition. If the read proceeds correctly, then the value is true. If there is an end-of-file (EOF) meaning that the end of the data has been reached, or if there is an error in reading, then the value returned is false and execution continues at the end of the loop.

Example -- Adding numbers in the input

int sum = 0;
int x;

while (cin >> x) {
   sum = sum + x;

cout << sum;

Testing the value from an input operation

Using cin in a while loop is a very common style of programming.

Use this pattern when reading. Another style, which is not generally used is Anti-idiom - Using cin in three places, instead of one.