1

I'm writing a casino game on C++ turbo (latest version for windows). So in one particular snippet of the program, the user is required to enter an initial amount strictly between 0 dollars and 100000 dollars.

I created a do-while loop with an embedded if statement:

do{
    cout << "\n\nEnter a deposit amount (between $0 and $100000) to play game : $";
    cin >> amount;
    if(amount<=0||amount>=100000)
        cout<<"Please re-enter your amount";
}while(amount<=0||amount>=100000);

The issue arises when the user (i.e. me) enters a character or a decimal; the program then loses control and it keeps looping indefinitely.

Question: How can I phrase an if-statement which requests the user to re-enter the amount if something other than an integer is entered? How can I, subsequently, prevent the program from going out of control?

Lucas Derraugh
  • 6,929
  • 3
  • 27
  • 43

3 Answers3

3

The problem is that when you call cin >> amount and the input is not numeric, the data is left in the buffer. Once your code loops back to the same operation, your read fails again, in an infinite loop.

To fix this problem you need to check the result of cin >> amount, like this:

if (cin >> amount) {
    ... // do something with amount
} else {
    cin.clear(); // unset failbit
    // Ignore some input before continuing
    cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}

Reference on the ignore function is here.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
2

You have to clear the error flag and ignore the characters.

For an example of cin.clear() see here.

do {
    cout << "Enter a deposit amount (between $0 and $100000) to play game : $";
    cin >> amount;

    if(amount<=0 || amount>=100000) {
        cout << "\nPlease re-enter your amount\n";
        cin.clear();
        cin.ignore(10000,'\n');
    }
} while(amount<=0 || amount>=100000);
Community
  • 1
  • 1
Danny_ds
  • 11,201
  • 1
  • 24
  • 46
1

Try this

    if(amount<=0||amount>=100000)
    {
        cout<<"Please re-enter your amount";
        cin.clear();
        cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    }
Support Ukraine
  • 42,271
  • 4
  • 38
  • 63