Итак, я делаю эту игру «Угадай число на С ++», которая выглядит следующим образом:
#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 << "Больше!"; </p>
Так что мой вопрос: Что вызывает это?