简体   繁体   中英

Check if input is not integer or number at all cpp

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM