C语言 使用 scanf() 进行输入验证

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15228388/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 05:34:06  来源:igfitidea点击:

Input validation using scanf()

cvalidationinputinteger

提问by Matthew

I have a program which accepts an integer from the user and uses this number in an addition operation.

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

The code which I am using to accept the number is this:

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

scanf("%d", &num);

How can I validate the input such that if the user enters a letter or a number with the decimal point, an error message is displayed on the screen?

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

回答by md5

You should use scanfreturn value. From man scanf:

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

Return Value

These functions return the number of input items successfully matched and assigned, which can be fewer than provided for, or even zero in the event of an early matching failure.

返回值

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

So it may look like this:

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

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

Notice it doesn't work for "numbers with the decimal point". For this you should rather use parsing and strtolfor instance. It may be a bit more complex.

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

回答by John Bode

Read your input as text using either scanfwith a %sconversion specifier or by using fgets, then use the strtollibrary function to do the conversion:

读你输入的使用是文本scanf%s转换符,或者使用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);