// Zig Herzog // Oct. 2012 // #include <iostream> using namespace std; // This program can be used to illustrate one of the nastier, unintended // properties of the cin object. The program below works fine as long as // the user enters indeed an integer number greater than zero and // terminates when the user enters an integer number less/equal to zero. // If though, the user enters something which includes a non-digit (like // a decimal point or letter), the program will loop forever executing // the two cout statements but ignoring all further user input. // // *********************************************************************** // If this happens, the only way to stop the program is by typing CTRL-C. // *********************************************************************** // // Remedy : Is the fail method of the cin object which I included // below but commented out. cin.fail() will return "true" // whenever the user's input conflicts with the data type // of the variable to receive the value. As a programmer you // control the action the program will take (here exit after // issuing a message. // // Note : for data type float or double and integer number is // acceptable but other things like two periods or letter // other then "e" or "E" etc. are not and produce the same // behavior. int main () { int i=1 ; while ( i > 0 ) { cout << "Give any positive integer value ( or 0 to terminate) : " ; cin >> i ; // if ( cin.fail() ) // { // cout << "\n\nYou messed up. Bye ....\n\n"; // return 1 ; // } cout << "i=" << i << endl ; } }