-3

I have written a code about guessing a secret number, but I have a problem when an alphabetic character is given as an input instead of an integer. It halts the program. What how can I resist this problem.

srand(time(0));
int a,secret;
secret=rand() % 10 +3;
do{
        cout<<"Guess the secret num between 1-10 + 3 : ";
cin>>a;
else if(a>secret)
{
    cout<<"Secret num is smaller!!"<<endl;
}
else if(a<secret) {
    cout<<"Secret num is greater !!"<<endl;
}

}
while(a!=secret)
cout<<"   "<<endl;
cout<<""<<endl;
    cout<<"Congratulations!!!! This is the secret num...."<<secret<<endl;
Jonathan Mee
  • 37,899
  • 23
  • 129
  • 288
HasaanCh
  • 23
  • 7

2 Answers2

0

You don't have to, but if you still want to solve the problem, you can stream the line and get the line in number only.

Answered by Jesse Good here:

I would use std::getline and std::string to read the whole line and then only break out of the loop when you can convert the entire line to a double.

#include <string>
#include <sstream>

int main()
{
  std::string line;
  double d;
  while (std::getline(std::cin, line))
  {
      std::stringstream ss(line);
      if (ss >> d)
      {
          if (ss.eof())
          {   // Success
              break;
          }
      }
      std::cout << "Error!" << std::endl;
  }
  std::cout << "Finally: " << d << std::endl;
}
Community
  • 1
  • 1
GLCraft
  • 144
  • 7
0

In your case, because 0 is outside the allowable range this is really simple:

  1. Initialize a to 0 and if a is 0 after extracting:
  2. clear cin
  3. ignore cin (Be careful to specify that you want to ignore up to the newline character: Cannot cin.ignore till EOF?)

Your final code should look something like this:

cout << "Guess the secret num between 1-10 + 3 : ";
cin >> a;

while (a != secret) {
    if (a == 0) {
        cin.clear();
        cin.ignore(std::numeric_limits<streamsize>::max(), '\n');
        cout << "Please enter a valid number between 1-10 + 3 : ";
    }
    else if (a < secret) {
        cout << "Secret num is smaller!!\nGuess the secret num between 1-10 + 3 : ";
    }
    else if (a < secret) {
        cout << "Secret num is greater !!\nGuess the secret num between 1-10 + 3 : ";
    }
    a = 0;

    cin >> a;
}

Live Example

Community
  • 1
  • 1
Jonathan Mee
  • 37,899
  • 23
  • 129
  • 288