C++ Notes: Reading numbers

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 += x;
   }
   
   cout << sum;

Anti-idiom: Checking for EOF instead of reading

The following code does almost the same thing as the code above, but it has disadvantages.
   int sum = 0;
   int x;
   
   cin >> x;       // BAD idiom for input.
   while (cin) {   // Required by inadequate Pascal I/O.
       sum += x;   // Should not be used in C++.
       cin >> x;
   }
   
   cout << sum;

See also

End-Of-File (EOF)