0

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);
}
CDAGeek
  • 59
  • 2
  • 14
  • 1
    Can the use enter an ENTER? Is ENTER a digit? Can the user enter a '$'? Is '$' a digit? After you validate the *string* entered (possibly with `isdigit()` for every character), convert the *string* to a number (`int`, possibly withy `strtol()`) and go from there. – pmg Mar 18 '13 at 11:05

1 Answers1

0

You can use the return value of scanf to determine whether the read was successful. So, there are two paths in your program, successful reading and failed reading:

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

In the first case, you do whatever your program logic says. In the else case, you have to figure out "what was the problem", and "what to do about it":

int guess;
if (scanf("%d", &guess) == 1)
{
    /* guess is 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, then the input wasn't a number */
    /* let's skip the current line. */
    while (!feof(stdin) && fgetc(stdin) != '\n');
}
Shahbaz
  • 46,337
  • 19
  • 116
  • 182