【问题标题】:Input validation using scanf() [duplicate]使用 scanf() 进行输入验证 [重复]
【发布时间】:2013-02-20 02:59:47
【问题描述】:

我有一个程序,它接受来自用户的整数并在加法运算中使用这个数字。

我用来接受号码的代码是这样的:

scanf("%d", &num);

如何验证输入,如果用户输入带小数点的字母或数字,屏幕上会显示错误消息?

【问题讨论】:

标签: c validation input integer


【解决方案1】:

使用带有%s 转换说明符的scanf 或使用fgets 将您的输入读取为文本,然后使用strtol 库函数进行转换:

#define MAX_DIGITS 20 // maximum number of decimal digits in a 64-bit integer

int val;
int okay = 0;

do
{
  char input[MAX_DIGITS+2]; // +1 for sign, +1 for 0 terminator
  printf("Gimme a number: ");
  fflush(stdout);
  if (fgets(input, sizeof input, stdin))
  {
    char *chk = NULL; // points to the first character *not* converted by strtol
    val = (int) strtol(input, &chk, 10);
    if (isspace(*chk) || *chk == 0)
    {
      // input was a valid integer string, we're done
      okay = 1;
    }
    else
    {
      printf("\"%s\" is not a valid integer string, try again.\n", input);
    }
  }
} while (!okay);

【讨论】:

    【解决方案2】:

    您应该使用scanf 返回值。来自man scanf

    返回值

    这些函数返回成功匹配和分配的输入项的数量,该数量可能少于提供的数量,在早期匹配失败的情况下甚至为零。

    所以它可能看起来像这样:

    if (scanf("%d", &num) != 1)
    {
        /* Display error message. */
    }
    

    请注意,它不适用于“带小数点的数字”。为此,您应该使用解析和 strtol 例如。可能有点复杂。

    【讨论】:

    • 我要告诉你十进制数字部分。我将检查 strtol 函数是如何工作的。谢谢
    • 那么在C语言中没有办法捕捉到这种情况吗?例如,在 Java 中,如果将浮点数提供给整数变量,则会引发异常。
    • @Matthew 问题是 scanf 不会将其读取为浮点数,它会将其读取为一个整数,后跟一个非整数('.'),因为你已经告诉它是一个整数。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多