# 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;

- Duplication. The input is read in two places, not one. Duplicate code creates an opportunity to update one and not the other when modifying the program.
- More code. The reading and testing is split between three lines instead of one. This makes it more difficult to read and maintain.
- Possible failure. The GCC I/O library, which is used by DevC++, does a good job with this. However, I've used systems that behaved differently using the `while (cin)` test, depending on whether there is whitespace after the last value. Think about it. The issue is rather subtle - how does the I/O system know that you aren't going to read the blanks after the last value? Well, it can't really know, so it makes some assumptions. Not all systems make the same assumptions about how to handle trailing whitespace after the last value.

## See also

End-Of-File (EOF)