【发布时间】:2018-02-09 15:25:31
【问题描述】:
我的程序应该从标准输入读取整数,然后
例子:
输入文件包含:"3 1 4 2 5\n"
函数输出:"{3, 1, 4, 2, 5}\n"
输入文件包含:"1 2 3 4 5 6 7 8\n"
函数输出:"{1, 2, 3, 4, 5, 6, 7, 8}\n"
输入文件包含:无(空文件)
函数输出:"No integers were provided.\n"
这适用于普通标准输入,直到我尝试使用看起来像这样的 .txt 文件从标准输入重定向中读取
输入.txt:1 2 3 4 5 6 7 8 9 10
在运行 GDB 时,我看到了这个:
它一直用 10 填充我的整数数组,直到我的程序崩溃。
这是我的代码:
#include <stdio.h>
void printNums() {
int nums[100];
int num;
int count = 0;
int x;
if ((scanf("%d", &num)) == EOF) {
printf("No integers were provided.\n");
return;
} else {
nums[count] = num;
count++;
}
while ((scanf("%d", &num) == 1)) {
if (num != ' ') {
nums[count] = num;
count++;
}
}
printf("{");
for (x = 0; x < count; x++) {
if (x == count - 1) {
printf("%c", nums[x]);
} else {
printf("%c, ", nums[x]);
}
}
printf("}\n");
}
请记住,我不允许导入除 stdio 以外的任何其他内容,并且最好使用用户 scanf 或 getchar
【问题讨论】:
-
它符合并运行良好。你确定删除了@usr2564301 的行号吗?
-
查找
scanf函数以查看它返回的内容。 -
您能否编辑您的代码以删除行号。当然,您的 IDE 中有一个选项。
-
比较
scanf与EOF或'\n'的返回值没有什么意义。
标签: c scanf infinite-loop