【发布时间】:2016-10-30 07:31:24
【问题描述】:
所以我正在用 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
所以我的问题是:这是什么原因造成的?
【问题讨论】: