Anti-idiom - Using cin in three places, instead of one

Anti-idiom: Checking for EOF without reading
The following bad style reads data from an input stream, but awkwardly puts the code for input into three statements instead of one. This creates unnecessary potential for bugs and maintenance problems. This style was used in the Pascal programming language, which didn't allow the combination of reading with testing, which C++ does.
   // Technically correct, BUT NOT GOOD style.
   int sum = 0;
   int x;
   
   cin >> x;       // BAD idiom for input.  Taken from
   while (cin) {   // (poor) Pascal I/O.  Do not use in C++.
       sum = sum + x;
       cin >> x;
   }
   
   cout << sum;
What's wrong with this?
This is code with a higher complexity, and therefore a higher cost.
Initial coding bugs more likely. Three statements instead of one.
Maintenance more difficult. Maintainer may have to change code in three places.
More difficult to read. Not only is the I/O in three places, but if the loop is large, they may not even be close.
Correct, simpler, idiom

   // This is a better idiom.  It groups all I/O in
   //    one statement, not three as above.
   //    It's more readable, and therefore more
   //    more maintainable and less likely to have bugs.
   int sum = 0;
   int x;
   
   while (cin >> x) {
       sum = sum + x;
   }
   
   cout << sum;

Posted on by