【问题标题】:How to read multiple number from a text file如何从文本文件中读取多个数字
【发布时间】: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 &lt; 7,如果inputNULL,不仅打印错误消息,还打印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 或其他。

标签: c arrays file-io


【解决方案1】:

将您的 while 循环条件更改为:

while( store < sizeof(line)/sizeof(int) && fscanf(input, "%d", &read) != EOF)

看起来你输入的数字比你有更多的空间。

【讨论】:

  • 这样可以防止我的 line[] 溢出?
猜你喜欢
  • 2012-10-06
  • 2015-08-11
  • 1970-01-01
  • 1970-01-01
  • 2014-04-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多