【发布时间】: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<std::streamsize>::max(), '\n');这两个重要点是相同的。
标签: c++