I'm working on a challenge problem from my textbook where I'm supposed to generate a random number between 1-10, let the user guess, and validate their response with isdigit(). I (mostly) got the program to work with the code below.
The main issue I ran into is that using isdigit() required the input to be stored as a char, which I then had to convert before the comparison so the actual number was compared and not the ASCII code for the number.
So my question is, since this conversion only works for numbers 0 - 9, how can I change the code to allow for the user to successfully guess 10 when that's the number that is generated? Or what if I wanted the game to have a range of 1-100 - how would I then accomplish this? Can I not verify the input with isdigit() if I'm using a possible range greater than 0-9? What is a better way to verify user input?
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <time.h>
int main(void) {
char buffer[10];
char cGuess;
char iNum;
srand(time(NULL));
iNum = (rand() % 10) + 1;
printf("%d\n", iNum);
printf("Please enter your guess: ");
fgets(buffer, sizeof(buffer), stdin);
sscanf(buffer, "%c", &cGuess);
if (isdigit(cGuess))
{
cGuess = cGuess - '0';
if (cGuess == iNum)
printf("You guessed correctly!");
else
{
if (cGuess > 0 && cGuess < 11)
printf("You guessed wrong.");
else
printf("You did not enter a valid number.");
}
}
else
printf("You did not enter a correct number.");
return(0);
}