validation - C number guessing game with isdigit() verification -


i'm working on challenge problem textbook i'm supposed generate random number between 1-10, let user guess, , validate response isdigit(). (mostly) got program work code below.

the main issue ran using isdigit() required input stored char, had convert before comparison actual number compared , not ascii code number.

so question is, since conversion works numbers 0 - 9, how can change code allow user guess 10 when that's number generated? or if wanted game have range of 1-100 - how accomplish this? can not verify input isdigit() if i'm using possible range greater 0-9? better way 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 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 valid number.");     }   }   else     printf("you did not enter correct number.");     return(0); } 

you can use return value of scanf determine whether read successful. so, there 2 paths in program, successful reading , failed reading:

int guess; if (scanf("%d", &guess) == 1) {     /* guess read */ } else {     /* guess not read */ } 

in first case, whatever program logic says. in else case, have figure out "what problem", , "what it":

int guess; if (scanf("%d", &guess) == 1) {     /* guess read */ } else {     if (feof(stdin) || ferror(stdin))     {         fprintf(stderr, "unexpected end of input or i/o error\n");         return exit_failure;     }     /* if not file error, input wasn't number */     /* let's skip current line. */     while (!feof(stdin) && fgetc(stdin) != '\n'); } 

Comments

Popular posts from this blog

sql - VB.NET Operand type clash: date is incompatible with int error -

SVG stroke-linecap doesn't work for circles in Firefox? -

python - TypeError: Scalar value for argument 'color' is not numeric in openCV -