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

是否有一种方法可以使用scanf()在C中计算用户输入的数量?,c,scanf,C,Scanf,我有以下代码块: printf("Enter size:\n"); scanf("%d",&size); 我的问题是,如何确保用户只输入一个整数?如果输入的整数数量不正确,我希望程序退出。scanf返回转换和赋值的数量,因此 scanf( "%d", &size ); 如果成功读取整数输入(见下文),将返回1;如果输入的内容不是整数(即键入的第一个非空白字符不是十进制数字),将返回0;如果输入流中存在错误,将返回EO

我有以下代码块:

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

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

scanf
返回转换和赋值的数量,因此

scanf( "%d", &size );
如果成功读取整数输入(见下文),将返回
1
;如果输入的内容不是整数(即键入的第一个非空白字符不是十进制数字),将返回
0
;如果输入流中存在错误,将返回
EOF

不过,这里需要注意的是,
%d
转换说明符将跳过前导空格,然后读取十进制数字,直到它看到任何非数字字符(不仅仅是空格)。因此,如果您输入类似于
“12w45”
scanf
将转换
12
并将其分配给
大小
,并返回
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" );
}

检查
scanf()
的返回值。您的意思是在一行中只输入一个整数,还是在整个标准输入流中只输入一个整数?