简体   繁体   English

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

[英]How to get integer input in an array using scanf in C?

I am taking multiple integer inputs using scanf and saving it in an array我正在使用 scanf 获取多个整数输入并将其保存在一个数组中

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

The input integers are separated by white spaces for example:输入整数由空格分隔,例如:

12 345 132 123

I read this solution in another post.我在另一篇文章中阅读了这个解决方案。

But the problem is the while loop is not terminating.但问题是 while 循环没有终止。

What's the problem with this statement?这个说法有什么问题?

OP is using the Enter or '\\n' to indicate the end of input and spaces as number delimiters. OP 使用Enter'\\n'来指示输入的结尾和空格作为数字分隔符。 scanf("%d",... does not distinguish between these white-spaces. In OP's while() loop, scanf() consumes the '\\n' waiting for additional input. scanf("%d",...不区分这些空格。在 OP 的while()循环中, scanf()消耗'\\n'等待额外的输入。

Instead, read a line with fgets() and then use sscanf() , strtol() , etc. to process it.相反,使用fgets()读取一行,然后使用sscanf()strtol()等来处理它。 ( strtol() is best, but OP is using scanf() family) 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();
}
//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;
}

You should try to write your statement like this:你应该试着像这样写你的陈述:

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

Please note the boundary check.请注意边界检查。

As people keep saying, scanf is not your friend when parsing real input from normal humans.正如人们一直说的那样,在解析来自正常人类的真实输入时,scanf 不是您的朋友。 There are many pitfalls in its handling of error cases.它在处理错误情况时存在许多陷阱。

See also:也可以看看:

There is nothing wrong with your code as it stands.您的代码没有任何问题。 And as long as the number of integers entered does not exceed the size of array, the program runs until EOF is entered.并且只要输入的整数个数不超过数组的大小,程序就会一直运行,直到输入EOF。 ie the following works:即以下作品:

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

As BLUEPIXY says, you must enter the correct keystroke for EOF.正如 BLUEPIXY 所说,您必须为 EOF 输入正确的击键。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM