我正在尝试使用读取未知数量的输入scanf
功能。
int a[100];
int i = 0;
while((scanf("%d", &a[i])) != '\n')
i++;
// Next part of the code
但是这个函数不会进入代码的下一部分,似乎有一个无限的 while 循环。
如何解决这个逻辑错误?还有其他替代方案吗scanf
like sscanf
将整数读入数组?
scanf返回已成功匹配和分配的输入项的数量,因此这样做是合理的:
while(scanf(...) == 1)
现在您希望能够读取多个数字,每个数字都在新行上定义。然后你可以简单地这样做:
int array[100];
int i = 0;
while(i < 100 && scanf("%d\n", &array[i]) == 1)
i++;
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).
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)