C++:Idioms-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.
  • Produces a value. The input operation with 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.
  • true. The value of cin >> x is true if a value was read into x.
  • false. The value of cin >> x is false if it was unable to read. There are several possible causes for a reading failure.
    • EOF. When there is no more data, the EOF (End-Of-File) condition occurs. Every stream of input has an end so this is a normal event. It happens when reading a disk file and the end is reached. It's also possible to signal an EOF from the console by entering a special key combination, which depends on which operating system and C++ library you are using. Generally, you can use Control-Z followed by Enter to send an EOF from the keyboard.
    • Bad data. The read may fail if the data isn't formatted correctly. For example, when trying to read a floating-point temperature and the user types "zero", the read will fail.
Posted on by