Skip to content

Instantly share code, notes, and snippets.

@Joeppie
Created August 19, 2017 10:35
Show Gist options
  • Save Joeppie/20101440ebb604cc6e16b2ba80626a23 to your computer and use it in GitHub Desktop.
Save Joeppie/20101440ebb604cc6e16b2ba80626a23 to your computer and use it in GitHub Desktop.
template<class T>
T ReadAndValidate() {
T n;
cout << "enter number:";
cout.flush();
cin >> n;
while (cin.fail() == 1 || n < 0) {
cin.clear();
cin.ignore(1000, '\n'); //throw away 1000 chars, or next end of line
cout << "\nincorrect value, enter another:";
cin >> n;
}
cout << "\n entered: " << n << endl;
}
@Joeppie
Copy link
Author

Joeppie commented Aug 19, 2017

Reads in a single value and does not allow user to enter incorrect values, prompts indefinitely until valid input has been registered.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment