Skip to content

Instantly share code, notes, and snippets.

@TheEyesightDim
Last active March 1, 2017 08:05
Show Gist options
  • Save TheEyesightDim/48417c4df92cdb681591 to your computer and use it in GitHub Desktop.
Save TheEyesightDim/48417c4df92cdb681591 to your computer and use it in GitHub Desktop.
Detect invalid input and clear input stream, C++ STL
do{
cout<<"Input \"1\" or \"0\": ";
cin >> scenario;
if(cin.fail() || scenario < 0 || scenario > 1){
cin.clear(); //clear failure state
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); //ignore and discard failed input up to and including newline
cout << "\nInput failed. Trying again..." << endl;
continue;
}
} while(false);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment