Raphael Raphael - 1 month ago 5
C++ Question

Guess the number - Infinite loop when bad read

So I am making this Guess the number game in c++ that looks like this:

#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;
}


*Sorry if the code is note very elegant

As you can see, the code works great until you enter a random caracter like '&' or 'j' or anything else that isn't an integer...Then it loops at cout<<"Bigger!";

So my question is: What is causing this?

Answer

Check this post, it is about the same problem. To summarize:

cin>>userInput;
if (cin.fail()) {
  cout<<"Invalid Entry, please try again."<<endl;
  cin.clear();
  cin.ignore(numeric_limits<streamsize>::max(), '\n');
}

Thanks ildjarn for pointing the missing ignore statement, I missed that part even though its clearly mentioned in the post I linked to!!