3

I have a program which generates random number and asks user to keep guessing it until he/she gets it right. I want it to keep accepting new values even if i incorrectly enter any other data type by handling the error cases.

My problem is that when i am trying to run the below program, as soon i input a character and hit enter, it goes into an infinite loop. I tried using cin.ignore() and cin.clear() but that just makes the program stop after the first entry.

Can anyone please help me understand what is going on and how to achieve the desired output? Thanks in advance.

#include <iostream>
#include <cstdlib>
#include <time.h>
using namespace std;

int main()
{
  int secret_num, guess;
  srand(time(NULL));
  secret_num=rand() %  101 + 0;
  cout<<"Enter your guess between 0 and 100: ";

do
 {
  if(!(cin>>guess))
  {
    cout<<" The entered value is not an integer"<<endl;
  }
  else if( isnumber(guess))
    {
      if(guess>secret_num)
        cout<<"Too high";
      else if(guess<secret_num)
        cout<<"too low";
    cout<<endl;
    }
 }
  while(secret_num!=guess);


  if((guess==secret_num)| (isnumber(guess)))
  {
    cout<<"yes the correct number is "<<secret_num<<endl;
  }

  return 0;
}

Edit: Here is a screenshot of what the output looks like with cin.clear() and cin.ignore(1000,'\n') in my code, when i enter a number after entering character twice. enter image description here

1
  • 1
    What is isnumber()? Commented Feb 15, 2016 at 16:29

4 Answers 4

1
    if (!(cin >> guess))
    {           
        cout << " The entered value is not an integer" << endl;
        cin.clear(); // clear must go before ignore

        // Otherwise ignore will fail (because the stream is still in a bad state)
        cin.ignore(std::numeric_limits<int>::max(), '\n'); 
    }

By default cin.ignore will ignore a single character. If they type more than 1 char, it won't be enough, that's why I've modified it a bit.

if ((guess == secret_num) | (isnumber(guess)))

| is a bitwise operator [OR]

|| is the logical operator [OR]

But I think what you actually want is && (AND)

if ((guess == secret_num) && (isnumber(guess)))
Sign up to request clarification or add additional context in comments.

1 Comment

Nope, it is still not working. I had tried using the same but with using 1000 instead of limits. It works fine if i keep entering characters. But as soon as i enter a number, it stops doing anything.
1

There're several problems.

  1. You should use cin.clear() and cin.ignore() as @José suggested.

  2. What's isnumber()? I guess it's returning false so no hint message (i.e. "Too high" and "too low") is printed out, looks like it stops although it's just waiting the next input. And isnumber() doesn't make sense to me. guess has been declared as an int, it has to be a number, doesn't it?

  3. if((guess==secret_num)| (isnumber(guess))) is unnecessary here. The loop won't end until the user input the correct number, this condition should have been statisfied.

1 Comment

Thanks a lot for pointed it out. When i was writing the code,i compiled my code with isnumeric(). The compiler showed an error saying that i should use isnumber() instead. I didn't bother to cross check it and hence this error. i removed isnumber() entirely and now the program works just fine.
0

You can use clear and flush

  if(!(cin>>guess))
  {
    cout<<" The entered value is not an integer"<<endl;
    cin.clear();
    fflush(stdin);
  }

This works if you are reading from console. Otherwise you can go with @José answer.

Comments

0

I would change the logic inside your loop as there are some useless tests. This works for me:

#include <iostream>
#include <limits>
#include <cstdlib> // You may take a look at <random> and <chrono>
#include <time.h>

using std::cout;
using std::cin;

int main() {

    srand(time(NULL));
    int secret_num = rand() %  101;
    cout << secret_num << '\n';
    cout << "Enter your guess between 0 and 100:\n";

    int guess = -1;
    do {
        cin >> guess;
        if ( cin.eof() ) 
            break;
        if ( cin.fail() ) {
            cout << "The entered value is not an integer, please retry.\n";
            // clear the error flag
            cin.clear();
            // ignore the rest of the line
            cin.ignore(std::numeric_limits<int>::max(),'\n');
            // clear the value of the variable
            guess = -1;
            continue;
        }
        // now we know that guess is a number
        if ( guess > secret_num )
            cout << "Too high\n";
        else if ( guess < secret_num )
            cout << "Too low\n";
        else {
            cout << "Yes the correct number is " << secret_num << std::endl;
            break;
        }
    } while ( true );

    return 0;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.