接受来自 scanf 函数的任意数量的输入 [英] Accepting any number of inputs from scanf function
问题描述
我正在尝试使用 scanf
函数读取未知数量的输入.
I am trying to read an unknown number of inputs using scanf
function.
int a[100];
int i = 0;
while((scanf("%d", &a[i])) != '\n')
i++;
// Next part of the code
但是这个函数不会进入下一部分代码,似乎有一个无限的while循环.
But this function is not going to next part of the code, seems like there is an infinite while loop.
我该如何解决这个逻辑错误?scanf
是否还有其他替代方法,例如 sscanf
将整数读入数组?
How Do I solve this logical error? Is there any other alternatives to scanf
like sscanf
to read integers into an array?
推荐答案
scanf
返回已成功匹配并分配的输入项的数量,因此这样做是合理的:
scanf
returns the number of input items that have been successfully matched and assigned, thus it is reasonable to do:
while(scanf(...) == 1)
现在您希望能够读取多个数字,每个数字都定义在新行上.然后你可以简单地这样做:
Now you want to be able to read multiple numbers, each defined on the new line. Then you could simply do this:
int array[100];
int i = 0;
while(i < 100 && scanf("%d\n", &array[i]) == 1)
i++;
请注意,只有在输入无效输入(例如字母 q
)或输入结束输入控制代码时才会停止读取,即 Ctrl+Z(在 Windows 上)或 Ctrl+D(在 Mac、Linux、Unix 上).
note that this reading will stop only if invalid input is entered (for example letter q
) or when you input the end-of-input control code, which is Ctrl+Z (on Windows) or Ctrl+D (on Mac, Linux, Unix).
这篇关于接受来自 scanf 函数的任意数量的输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!