C 猜数字游戏,使用 isdigit() 验证

标签 c validation

我正在解决教科书中的一个挑战问题,我应该生成一个 1-10 之间的随机数,让用户猜测,并使用 isdigit() 验证他们的响应。我(大部分)让程序与下面的代码一起工作。

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

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

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

最佳答案

可以通过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');
}

关于C 猜数字游戏,使用 isdigit() 验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15475233/

相关文章:

c - 在 C 中对 pthreads 使用互斥锁/解锁和广播

objective-c - 将字符串转换为 float ,而不使用 c 中的内置函数

validation - WSO2 API Manager - token 限制 20KPerToken

javascript - Jquery 实时验证

javascript - 最小最大价格范围验证不适用于 jquery.validate.js

c - 进入 NIT 参数编号 9 时有非法值

c - 如何知道中断是否被禁用?

C程序不会按升序排列数字

c# - 正则表达式号码电话

ruby-on-rails - Rails (RoR) ActiveRecord 自定义验证