0

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?

Raphael
  • 143
  • 1
  • 2
  • 15
  • possible duplicate of [While loop with try catch fails at bad cin input](http://stackoverflow.com/questions/2292202/while-loop-with-try-catch-fails-at-bad-cin-input) – ildjarn May 21 '11 at 00:15

3 Answers3

7

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!!

Community
  • 1
  • 1
user258808
  • 734
  • 4
  • 5
2

See this FAQ: How can I get std::cin to skip invalid input characters?

ildjarn
  • 62,044
  • 9
  • 127
  • 211
0

cin>>userInput;

If it cannot read an integet, the bad bit is set for the cin stream. You should check and clear afterwords.

if ( cin.fail() )
{
   cin.clear();
   try again
}
George Kastrinis
  • 4,924
  • 4
  • 29
  • 46
  • 1
    What good does calling `clear` do if you don't remove the invalid input from the input buffer? – ildjarn May 21 '11 at 00:45
  • 1
    The 'try again' part is getting new input from the user. Your answer needs to show how to first remove the old, invalid input from the buffer first. – ildjarn May 21 '11 at 00:51