//R. A. Hillyard //cinTest3.cpp //program to demonstrate how to recover from //input errors using the cin member functions // //part three - handle case where there is extra data //on the input stream. i.e. 55.66 or 76Hello #include<iostream> //new style of include #include<cctype> using namespace std; int main() { char charChoice; //hold character entered by user int intChoice; //hold int entered by user char next; do { cout << "\n*** Welcome to some program ***\n\n"; bool flag = true; do { cout << "Enter an integer : "; cin >> intChoice; if(cin.fail()) //had a failure reading the input { cin.clear(); //must reset stream after failure cout << "Invalid input - try again\n"; cin.get(next); //now get any remaining chars from the stream while(next != '\n') //reads until end of line cin.get(next); } else { cin.get(next); //now get any remaining chars from the stream while(next != '\n') //reads until end of line cin.get(next); flag = false; } }while(flag); cout << "You entered a: " << intChoice << endl; cout << "\nTry again?? [Y/N]: "; cin >> charChoice; charChoice = toupper(charChoice); }while(charChoice != 'N'); }//end main //run the program with the following data and note the results //test1 - enter 5 (valid integer) //test2 - enter c (char - invalid integer - catch it this time) //test3 - enter 55.66 (should work now) //test4 - enter 76Hello (should work now)