Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
331 views
in Technique[技术] by (71.8m points)

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

I am making a simple guess the number game using C++. My program checks if the user input is an integer or not. But when I input for example "abc" the program keeps saying: "Input a number!" instead of saying it once and let the user input something again..

Code:

#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!
" << endl;
        exit(0);
    }else{
        if(chances > 0){
            cout << "Wrong answer, try again!
" << 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();
}

Thanks in advance.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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(), '
');
      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(), ' '); line will ignore everything until the next int number.. Therefore it will not loop anymore..


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...