如何在C中使用scanf在数组中获取整数输入?

问题描述 投票:3回答:4

我正在使用scanf接收多个整数输入并将其保存在数组中

while(scanf("%d",&array[i++])==1);

例如,输入整数用空格分隔:

12 345 132 123

我在另一篇文章中阅读了此解决方案。

但是问题是while循环没有终止。

此语句有什么问题?

c scanf
4个回答
8
投票

OP使用Enter'\n'表示输入的结尾和空格作为数字定界符。 scanf("%d",...不能区分这些空白。在OP的while()循环中,scanf()消耗'\n'等待其他输入。

相反,使用fgets()读取一行,然后使用sscanf()strtol()等进行处理。 (最好使用strtol(),但OP使用的是scanf()系列)

char buf[100];
if (fgets(buf, sizeof buf, stdin) != NULL) {
  char *p = buf;
  int n;
  while (sscanf(p, "%d %n", &array[i], &n) == 1) {
     ; // do something with array[i]
     i++;  // Increment after success @BLUEPIXY
     p += n;
  }
  if (*p != '\0') HandleLeftOverNonNumericInput();
}

4
投票
//Better do it in this way
int main()
{
  int number,array[20],i=0;
  scanf("%d",&number);//Number of scanfs
  while(i<number)
  scanf("%d",&array[i++]);
  return 0;
}

1
投票

您应该尝试这样写语句:

while ( ( scanf("%d",&array[i++] ) != -1 ) && ( i < n ) ) { ... }

请注意边界检查。

正如人们一直说的那样,在解析正常人的真实输入时,scanf不是您的朋友。在处理错误案例时有很多陷阱。

另请参见:


0
投票

您的代码没有错。只要输入的整数数量不超过数组的大小,程序就会运行直到输入EOF。即以下作品:

int main(void)
{
    int array[20] = {0};
    int i=0;
    while(scanf("%d", &array[i++]) == 1);
    return 0;   
}  

正如BLUEPIXY所说,您必须输入正确的EOF击键。

© www.soinside.com 2019 - 2024. All rights reserved.