C编号猜测游戏与isdigit()validation

我正在从我的教科书中解决挑战问题,我应该在1-10之间生成一个随机数,让用户猜测,并用isdigit()validation他们的响应。 我(大多数)得到了程序来使用下面的代码。

我遇到的主要问题是使用isdigit()需要将输入存储为char,然后我必须在比较之前进行转换,以便比较实际数字而不是数字的ASCII代码。

所以我的问题是,由于此转换仅适用于数字0 – 9,我如何更改代码以允许用户成功猜出10,这是生成的数字? 或者,如果我希望游戏的范围为1-100,那该怎么办呢? 如果我使用的可能范围大于0-9,是否可以使用isdigit()validation输入? validation用户输入的更好方法是什么?

#include  #include  #include  #include  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); } 

您可以使用scanf的返回值来确定读取是否成功。 因此,您的计划中有两条路径,即成功阅读和阅读失败:

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

在第一种情况下,您可以执行程序逻辑所说的任何操作。 在else情况下,你必须弄清楚“问题是什么”,以及“该怎么办”:

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