cin >> quarters; /* user types "four" */ /* now cin has failed, and NO characters have been read */ cout << "Bad input. Try again!"; cin.clear(); /* now the failure has been reset, and cin STILL contains the same characters */ cin >> quarters; /* user types: 4 */ /* now cin has the characters "four4" */ /* cin STILL fails */
To fix this problem takes more than just clearing the failed state--one would also have to read all bad input. The strategy in the book--to read the input with getline--is a better method for writing robust programs. Moral: Don't trust books that are written by people who don't code themselves.