所以我猜这个用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;
}
Run Code Online (Sandbox Code Playgroud)
*对不起,如果代码是非常优雅的
正如你所看到的,代码工作得很好,直到你输入一个随机的字符,如'&'或'j'或其他任何不是整数的...然后它循环在cout <<"Bigger!";
所以我的问题是:是什么导致了这个?
查看这篇文章,它是关于同样的问题.总结一下:
cin>>userInput;
if (cin.fail()) {
cout<<"Invalid Entry, please try again."<<endl;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
Run Code Online (Sandbox Code Playgroud)
感谢ildjarn指出丢失的忽略声明,我错过了那部分,即使它在我链接的帖子中明确提到!!