如何在C中使用scanf获取数组中的整数输入? [英] How to get integer input in an array using scanf in C?
问题描述
我正在使用 scanf 获取多个整数输入并将其保存在一个数组中
I am taking multiple integer inputs using scanf and saving it in an array
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.
但问题是 while 循环没有终止.
But the problem is the while loop is not terminating.
这句话有什么问题?
推荐答案
OP 使用 Enter 或 '\n'
来表示输入和空格的结束数字分隔符.scanf("%d",...
不区分这些空格.在 OP 的 while()
循环中,scanf()
消耗 '\n'
等待额外输入.
OP is using the Enter or '\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.
相反,使用fgets()
读取一行,然后使用sscanf()
、strtol()
等来处理它.(strtol()
是最好的,但 OP 使用的是 scanf()
系列)
Instead, read a line with fgets()
and then use sscanf()
, strtol()
, etc. to process it. (strtol()
is best, but OP is using scanf()
family)
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();
}
这篇关于如何在C中使用scanf获取数组中的整数输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!