0

I'm creating (what should be) a very simple code to calculate some movie prices. I need the following input variables : movie_title, adult_tickets_sold, child_tickets_sold. I'm trying to add exceptions in case someone enters something other than an integer for the tickets sold variables. Something like this in python:

favorite_number = None
while True:
    tmp = input("Enter your favorite number: ")
    try:
        favorite_number = int(tmp)
        break
    except ValueError:
        print("Enter an integer value please...")

And this is the loop I have now in C++ (only working on one input at the moment):

while (con==true){
        cout << "How many adult tickets sold? " << endl;
        cin >> bigBoy;

        if (cin.fail()){
            cout << "\nYou entered text instead of a number!\nLet's try that again!\n\n"<< endl;
            cout << "Please enter an integer: ";
            cin >> bigBoy;
            continue;
        }
        cout << "How many children tickets sold? " << endl;
        cin >> lilSquirt;

        con=false;
    }

Whenever the if-statement is triggered, it completely ignores the 'cin's and infinitely prints this:

You entered text instead of a number!
Let's try that again!


Please enter an integer: How many adult tickets sold?

No idea why this is happening.

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
MaxAMilli
  • 21
  • 2
  • 1
    add `cin.clear();` before `cin >> bigBoy;` – brc-dd Sep 08 '20 at 04:23
  • This doesn't address the question, but the usual idiom for checking input is to use the conversion from a steam to a `bool`. Like this: `while (!(std::cin >> bigBoy)) { /* stuff to clean stream and re-prompt */ }`. – Pete Becker Sep 08 '20 at 13:00

1 Answers1

0
 if (cin.fail()){
        cin.clear();
        cin.ignore(22,'\n');
        cout << "\nYou entered text instead of a number!\nLet's try that again!\n\n"<< endl;
        cout << "Please enter an integer: ";
        cin >> bigBoy;
      //  continue;
    }

you have to clear the cin. Also comment out continue statement if you want adult ticket and child ticket both .