Reputation: 11
int n;
do
{
cout << "What height should the pyramid be? ";
cin >> n;
} while (n <= 1 || n > 23);
So as you can see it should only take values between 0 and 24, which works fine. If you put in an extremely large value though, it repeats infinitely. Is there a way to safeguard against abusing that at the input stage?
(side note, anyone know why "n < 0" allows 0 as a value in this instance?)
Upvotes: 0
Views: 65
Reputation: 13040
The failbit
of cin
will be set if the input number is too large to be stored in an int
, then following cin >> n
will always fail. You can use cin.clear()
to clear the failbit
before cin >> n
:
int n;
do
{
cin.clear(); // <-----
cout << "What height should the pyramid be? ";
cin >> n;
} while (n <= 1 || n > 23);
Upvotes: 1