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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25141168/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 11:15:56  来源:igfitidea点击:

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

cscanf

提问by Ross

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?

这个说法有什么问题?

回答by chux - Reinstate Monica

OP is using the Enteror '\n'to indicate the end of input and spaces as number delimiters. scanf("%d",...does not distinguish between these white-spaces. In OP's while()loop, scanf()consumes the '\n'waiting for additional input.

OP 使用Enteror'\n'来指示输入的结尾和空格作为数字分隔符。 scanf("%d",...不区分这些空白。在 OP 的while()循环中,scanf()消耗'\n'等待额外输入的时间。

Instead, read a line with fgets()and then use sscanf(), strtol(), etc. to process it. (strtol()is best, but OP is using scanf()family)

取而代之的是,读了线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 != '
//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;
}
') HandleLeftOverNonNumericInput(); }

回答by Shreemay Panhalkar

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

回答by Adrian

You should try to write your statement like this:

你应该试着像这样写你的陈述:

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

Please note the boundary check.

请注意边界检查。

As people keep saying, scanf is not your friend when parsing real input from normal humans. There are many pitfalls in its handling of error cases.

正如人们一直说的那样,在解析来自正常人类的真实输入时,scanf 不是您的朋友。它在处理错误情况时存在许多陷阱。

See also:

也可以看看:

回答by ryyker

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. i.e. the following works:

您的代码没有任何问题。并且只要输入的整数个数不超过数组的大小,程序就会一直运行,直到输入EOF。即以下作品:

##代码##

As BLUEPIXY says, you must enter the correct keystroke for EOF.

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