0
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?)

  • `(...) & cin` should break it, but you still do not have correct `n`. – apple apple Dec 13 '18 at 03:34
  • You omitted the datatype (`int`, `long`, &c) of `n` from your question. – Richard Dec 13 '18 at 03:38
  • 1
    `std::cin` is pretty weird (it uses bad flags rather than exceptions... for speed reasons?). [See here.](https://stackoverflow.com/questions/10349857/how-to-handle-wrong-data-type-input) – Mateen Ulhaq Dec 13 '18 at 03:44
  • Thank you for linking that question, I mustn't have looked as hard as I thought... Cheers for the quick and helpful comments all! – returnInfinite Dec 13 '18 at 03:55
  • 1
    @MateenUlhaq you can [turn on exceptions](https://en.cppreference.com/w/cpp/io/basic_ios/exceptions), though – Remy Lebeau Dec 13 '18 at 03:56
  • Can you provide an example of an "extremely large value"? I am assuming that the answer provided below is correct but it would good to confirm. – Matt Dec 13 '18 at 04:28

1 Answers1

1

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);
xskxzr
  • 12,442
  • 12
  • 37
  • 77