当cin不是int时,C ++程序会保持循环

时间:2015-09-22 15:19:37

标签: c++

我正在使用C ++对数字游戏做一个简单的猜测。 我的程序检查用户输入是否为整数。 但是当我输入例如“abc”时,程序一直说:“输入一个数字!”而不是说一次,让用户再次输入内容..

代码:

#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;

int chances = 3;
void ask();
void checkAnswer(int ans);
void defineNumber();
int correctAnswer;

void defineNumber(){
    srand(time(0));
    correctAnswer = rand()%11;
}

void checkAnswer(int ans){
    if(ans == correctAnswer){
        cout << "The answer was right!\n" << endl;
        exit(0);
    }else{
        if(chances > 0){
            cout << "Wrong answer, try again!\n" << endl;
            chances--;
            ask();
        }else{
            cout << "You lost!" << endl;
            exit(0);
        }
    }
}

void ask(){
    int input;
    cout << correctAnswer << endl;
    try{
        cin >> input;
        if(input > 11 || input < 0){
            if(!cin){
                cout << "Input a number!" << endl; //HERE LIES THE PROBLEM
                cin.clear(); //I TRIED THIS BUT DIDN'T WORK AS WELL
                ask();
            }else{
                cout << "Under 10 you idiot!" << endl;
                ask();
            }
        }else{
            checkAnswer(input);
        }
    }catch(exception e){
        cout << "An unexpected error occurred!" << endl;
        ask();
    }
}

int main(){
    cout << "Welcome to guess the number!" << endl;
    cout << "Guess the number under 10: ";
    defineNumber();
    ask();
}

提前致谢。

1 个答案:

答案 0 :(得分:0)

试试这个:

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();
}

并且不要忘记在开头使用它:#include <climits>

cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');行将忽略所有内容,直到下一个int数。因此它将不再循环..