[Solved] C++ program keeps looping when cin is not an int


Try this:

try{
    cin >> input;
    if (cin.good()) {
      if(input > 11 || input < 0) {
        cout << "Under 10 you idiot!" << endl;
        ask();
      } else {
        checkAnswer(input);
      }

    } else {
      cout << "Input a number!" << endl;
      cin.clear();
      cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
      ask();
      }

}catch(exception e){
    cout << "An unexpected error occurred!" << endl;
    ask();
}

and don’t forget to use this at the beginning: #include <climits>

The cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); line will ignore everything until the next int number.. Therefore it will not loop anymore..

3

solved C++ program keeps looping when cin is not an int