所以我正在用 C++ 制作这个猜数字游戏,看起来像这样:
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
srand(time(0));
int secretNumber = rand() % 100 + 1; //Generate "Random number"
int nbrOfGuesses = 0;
int userInput;
cout<<"\t************************************"<<endl;
cout<<"\t* *"<<endl;
cout<<"\t* Guess the number! *"<<endl;
cout<<"\t* *"<<endl;
cout<<"\t************************************"<<endl;
cout<<endl;
cout << "Try to find the secret int number: " << endl;
//While input is good
while(cin.good())
{
//Do this
do {
cin>>userInput;
nbrOfGuesses++;
if (userInput>secretNumber)
cout << "Smaller!\n";
else if(userInput<secretNumber)
cout << "Bigger!\n"; // <-- Infinite loop here when you enter something other than an integer
else //Also using this as a backup of (cin.good())
cout << "Something went wrong with the read";
break;
} while(userInput!=secretNumber);
cout << "\nCongratulations! You got it in " << nbrOfGuesses << " guesses\n";
}
system("pause");
return 0;
}
*抱歉,如果代码非常优雅
如您所见,代码运行良好,直到您输入一个随机字符,如“&”或“j”或任何其他非整数...然后它在 cout<<"Bigger!"; 处循环。
所以我的问题是:造成这种情况的原因是什么?
最佳答案
检查 this post ,这是关于同样的问题。总结:
cin>>userInput;
if (cin.fail()) {
cout<<"Invalid Entry, please try again."<<endl;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
感谢 ildjarn 指出缺少的忽略语句,我错过了那部分,尽管它在我链接的帖子中明确提到了!!
关于c++ - 猜数字 - 读取错误时无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6078727/