You just try to read an int
with cin >> [int variable]
, and make sure it succeeded. If not, wash, rinse, and repeat:
int i; while (!(cin >> i)) { cout << "Enter a valid integer, try again: "; cin.clear(); cin.ignore(std::numeric_limits<int>::max(), '\n'); } return i;
That will work, but will return 12
when given input like
12 a
because it will read the 12 and stop at a
. If you do not want to just “get as much as you can” and want to read the whole line (which is what the Java snippet apparently does) then you can use std::getline
and try to convert the resulting string into an integer with std::stoi
:
string line; int integer = 0; while (std::getline(cin, line)) try { integer = std::stoi(line); break; } catch (...) { cout << "Enter an integer, try again: "; } return integer;
That way will not return on input like
143 bbc
because it will try to convert the entire line 143 bbc
to an integer and tell the user to try again because bbc
can’t be converted to an integer. It will only return when the entire line is integer input.
You can actually accomplish this by using regexen like the Java example does, but I think it’s a waste to pull out regexes for this simple task.
Edit:
If you want to reject decimal input instead of truncating it, you can convert the input to a double
and check to make sure it doesn’t have a decimal part:
string line; double d = 0; while (std::getline(cin, line)) try { d = std::stod(line); if (std::fmod(d, 1) != 0) throw 0; break; } catch (...) { cout << "Enter an integer, try again: "; } return d;