有没有一种方法可以使用 scanf() 来计算 C 中用户输入的数量?

Is there a way to count the number inputs from the user in C with scanf()?

我有以下代码块:

printf("Enter size:\n");
scanf("%d",&size);

我的问题是,如何保证用户只输入一个整数?如果他们输入的整数个数不正确,我希望程序退出。

scanf returns 转换和赋值的次数,所以

scanf( "%d", &size );

将 return 1 如果您成功读取整数输入(见下文),0 如果您输入的不是整数(即第一个 non-whitespace 您键入的字符不是十进制数字),或者 EOF 如果输入流出现错误。

这里是您需要注意的地方,但是 - %d 转换说明符将跳过前导空格,然后读取十进制数字,直到它看到 any non-digit 字符(不仅仅是空格)。因此,如果您输入类似 "12w45" 的内容,scanf 将转换并将 12 分配给 size 和 return 1 以指示成功,即使您可能想要拒绝整个输入。

您需要在输入后立即检查字符,如下所示:

int tmp;
char chk;

int n = 0;

if ( (n = scanf( "%d%c", &tmp, &chk )) == 2 ) // up to 2 conversions and assignments
{
  if ( isspace( chk ) ) // only thing following your input is whitespace
    size = tmp;
  else
    fprintf( stderr, "non-numeric character in input, try again\n" );
}
else if ( n == 1 ) // only thing following input was EOF
{
  size = tmp;
}
else if ( n == 0 ) // first non-whitespace character was not a digit
{
  fprintf( stderr, "non-numeric character in input, try again\n" );
}
else
{
  fprintf( stderr, "Error on input stream\n" );
}

您将需要使用 scanf 以外的东西来验证输入。您可能最好使用 fgets 将输入读取为文本,然后使用 strtol(对于整数类型)或 strtod(对于浮点类型)转换该文本 - 它们会给您检查格式错误的输入的机会。示例:

char inbuf[12]; // up to 10 decimal digits plus sign and terminator
int size;
int tmp;
char *chk; // will point to the first character *not* converted by strtol

if ( fgets( inbuf, sizeof inbuf, stdin ) ) // read input as text
{
  tmp = strtol( inbuf, &chk, 10 ); // convert string to integer
  if ( !isspace( *chk ) && *chk != 0 )
  {
    fprintf( stderr, "non-numeric character in input, try again\n" );
  }
  else
  {
    size = tmp;
  }
}
else
{
  fprintf( stderr, "error on input\n" );
}