Skip to content

Instantly share code, notes, and snippets.

@RolandWarburton
Last active October 1, 2019 11:47
Show Gist options
  • Save RolandWarburton/5d372caaa71e46c52cc9d45be142bffe to your computer and use it in GitHub Desktop.
Save RolandWarburton/5d372caaa71e46c52cc9d45be142bffe to your computer and use it in GitHub Desktop.
read int validator
int readInt(string output = "")
{
cout << output;
int input = 0;
bool valid = false;
// while the input isnt correct. keep asking
// istream (cin) will flag itself if there was an issue reading
// eg. a char was entered
while (!valid)
{
while (!(cin >> input) && !valid)
{
valid = false;
cin.clear();
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
cout << "wrong number: ";
}
if((input >= -1 && input <= 10))
{
valid = true;
}
else
{
cout << "out of bounds number: ";
}
}
return input;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment