【发布时间】:2013-03-10 08:06:16
【问题描述】:
所以这是我的代码,我不断收到分段错误。 如何格式化此代码以从文件中读取一组数字?
我的输入如下所示:82、46、71、56、44、12、100 62、67、64、65、62、39、68 68、90、78、57、76、45、82 等
#include <stdio.h>
int main ()
{
FILE *input = fopen("input.txt", "r");
int line[7];
int store = 0, read;
if(!input)
{
printf("Error: Filename \"input.txt\" not found!\n");
}
store = 0;
while(fscanf(input, "%d", &read) != EOF)
{
line[store] = read;
store++;
}
printf("%d %d %d %d %d %d %d\n", line[0], line[1], line[2], line[3], line[4], line[5], line[6]);
return(0);
}
【问题讨论】:
-
文件格式是什么?检查循环中的
store < 7,如果input是NULL,不仅打印错误消息,还打印exit(1)。并且如果fscanf在没有输入错误的情况下读取int失败,它的返回值为0,所以检查fscanf(...) == 1。 -
for 循环中似乎没有任何防护措施防止您溢出 line[]。如果您的文件中的数字超过 7 个怎么办?
-
好的,谢谢!我的输入如下所示:82、46、71、56、44、12、100 62、67、64、65、62、39、68 68、90、78、57、76、45、82 等。这对我有帮助案例呢? (另外,如果你知道,我该如何阅读下一行等等?)
-
哦,那里每行有七个整数,但我不知道为什么我不能这样显示。
-
文件中有逗号吗?那么你的
fscanf将永远无法使用第一个逗号并返回 0,直到程序出现段错误,因为store是 1347 或其他。