如何在C中检查scanf中的额外输入

  • 本文关键字:scanf c scanf
  • 更新时间 :
  • 英文 :


我正在使用scanf()来获取x的值,我想检查是否输入了除单个整数以外的任何值;如果是,我想重新输入。

以下是我目前拥有的:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char const *argv[])
{
int x;
char c;
int input = scanf("%i%c", &x, &c);
while (input != 2 || c != 'n')
{
input = scanf("%i%c", &x, &c);
}
printf("x = %in", x);
}

目前,当我输入两个用空格分隔的整数时,例如23 43,程序会打印出43,而不是再次要求输入。

如有任何帮助,我们将不胜感激。

谢谢。

考虑使用strtol()来检查字符串中的所有字符是否已转换为数字。使用fgets或任何其他读线器读取字符串,并从中提取数字:

char buffer[4096];
fgets(buffer, sizeof(buffer), stdin);
char *endptr;
long result = strtol(buffer, &endptr, 10);
if(*endptr != '') { /* There is more input! */ }

作为奖励,您可以读取非十进制数字,还可以检查输入的数字是否在可接受的范围内。

你需要用其他方法来做这件事,因为int只允许单个数字。例如:1000你可以像:1000 2000那样做,但还有另一种方法可以询问用户要键入的数字,然后循环扫描数字,然后你可以在这里做任何你想做的事情。例如:

#include <stdio.h>
int main()
{
int loopTime = 0;
int temp = 0;
int result = 0;
printf("Enter the count of number you need to enter: ");//the number of times scanf going to loop
scanf("%d", &loopTime);
printf("Now enter the numbers you going to store but after every number you need to press entern");
for (int i = 0; i < loopTime; i++)
{
scanf("%d", &temp);
result += temp;
}
printf("The Result is: %i", result);
return 0;
}

最新更新