【问题标题】:C++ program keeps looping when cin is not an int当 cin 不是 int 时,C++ 程序不断循环
【发布时间】:2015-09-22 23:55:13
【问题描述】:

我正在使用 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();
}

提前致谢。

【问题讨论】:

  • infinite loop with cin 的可能重复项
  • 不,因为 Smeilliz 在那个问题上的回答与其他人不同。
  • 而当时的答案是不正确的。现在不是了,cin.clear();cin.ignore(std::numeric_limits&lt;std::streamsize&gt;::max(), '\n'); 这两个重要点是相同的。

标签: c++


【解决方案1】:

试试这个:

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 &lt;climits&gt;

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

【讨论】:

  • clear() 清除了错误条件,但“abc”仍然存在于缓冲区中,并将导致下一次输入出现新错误。检查函数ignore 是否跳过输入。
  • 但我需要让用户再次输入,当答案错误时。这就是我再次调用 ask 函数的原因,我希望输入会被“重置”。知道如何解决这个问题吗?
  • cin.ignore(std::numeric_limits&lt;std::streamsize&gt;::max(), '\n'); 更便携,恕我直言
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-11-05
  • 1970-01-01
  • 1970-01-01
  • 2018-06-20
  • 1970-01-01
  • 1970-01-01
  • 2013-03-13
相关资源
最近更新 更多