所以我提出這個猜測的數字遊戲,在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!」;
所以我的問題是:這是什麼原因造成的?
可能重複[循環和嘗試捕捉在壞CIN輸入失敗(http://stackoverflow.com/questions/2292202/while-loop-with-try-catch-fails-at-bad- cin-input) – ildjarn 2011-05-21 00:15:08