-2

I've created a guessing game where you have to guess randomly generated number in range from 1 to 100. I also managed to restrict a user if they enter a number that is out of the range, and requires new input. The problem is when you accidentally enter letters or symbols. Then it enters an infinite loop. I tried:

while(x<1 || x>100 || cin.fail())//1. tried to test if input failed (AFAIU it checks if input is expected type and if it is not it fails)
while(x<1 || x>100 || x>='a' && x<='z' || x>='A' && <='Z') // 2. tried to test for letters at least
while(x<1 || x>100 x!=(int)x)//3. to test if it is not integer
{ cout<<"Out of range";
  cin>>x;
}
πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
edoo
  • 7
  • https://stackoverflow.com/questions/39282953/how-to-reset-stdcin-when-using-it – drescherjm Nov 03 '18 at 23:22
  • 1
    Don't read directly from `std::cin` using streaming operators - any "accidental" input puts `std::cin` in an error condition, which must be cleared before discarding bad input. Instead, read all data as a `std::string`, using (for example) `std::getline(std::cin, some_string)`. Then parse that string to extract whatever input is needed and discard the rest. Using the string to create a `std::strstream` (which does allow you to read from the string using streaming operators, but makes error checking easier) offers one way to parse the string. – Peter Nov 03 '18 at 23:32

1 Answers1

2

For one solution, you could try and use isdigit. This checks to see if input is actually a number. So you can do something like:

if(!(isdigit(x))){
   cout << "That is not an acceptable entry. \n";
   continue;
}

EDIT: I should say, that after researching this, I realized that for isdigit to work, the entry needs to be a char. However, this can still work if you convert the char into an int after it discovers that it's an int. Example:

if(!(isdigit(x))){
       cout << "That is not an acceptable entry. \n";
       continue;
}
else{
     int y = x - '0';
}

That int y = x - '0' might seem odd; but it's there because you have to convert the char to an int, and according to the ASCII coding, to do so, you subtract the character '0' from the desired number. You can see that here: Convert char to int in C and C++

Little Boy Blue
  • 311
  • 4
  • 17