【问题标题】:How can I read an array of data from a text file in my code in C programming?如何在 C 编程的代码中从文本文件中读取数据数组?
【发布时间】:2018-03-11 15:45:19
【问题描述】:

我有一个代码可以读取包含一堆数字的文本文件。我使用下面的代码来访问它,但这只会抓住第一行。

我还有 99 行数据要访问。如何让它读取其他 99 行数据?

fscanf(fp1,"%lf,%lf,%lf,%lf",&a,&b,&c,&d);

【问题讨论】:

  • 你有没有试过从文件中逐行获取数据并用 fscanf 解析每一行数据?
  • 正如我所提到的,还有 99 行数据需要处理。我不知道如何有效地做你提到的。

标签: c arrays text


【解决方案1】:

正如 elia 在 cmets 中提到的,最好的策略是阅读整行 然后用sscanf解析它。

char buffer[1024];
while(fgets(buffer, sizeof buffer, fp1))
{
    if(sscanf(buffer,"%lf,%lf,%lf,%lf",&a,&b,&c,&d) != 4)
    {
        fprintf(stderr, "Invalid line format, ignoring\n");
        continue;
    }

    printf("a: %lf, b: %lf, c: %ld, d: %lf\n", a, b, c, d);
}

另一种选择是继续阅读直到\n

while(1)
{
    if(fscanf(fp1,"%lf,%lf,%lf,%lf",&a,&b,&c,&d) != 4)
    {
        fprintf(stderr, "Invalid line format, ignoring\n");
        if(clear_line(fp1) == 0)
        {
            fprintf(stderr, "Cannot read from fp1 anymore\n");
            break;
        }
        continue;
    }

    printf("a: %lf, b: %lf, c: %ld, d: %lf\n", a, b, c, d);

    if(clear_line(fp1) == 0)
    {
        fprintf(stderr, "Cannot read from fp1 anymore\n");
        break;
    }
}

clear_line 看起来像这样:

int clear_line(FILE *fp)
{
    if(fp == NULL)
        return 0;

    int c;
    while((c = fgetc(fp)) != '\n' && c != EOF);

    return c != EOF;
}

【讨论】:

    【解决方案2】:

    这个:

    fscanf(fp1,"%lf,%lf,%lf,%lf",&a,&b,&c,&d);
    

    提示输入文件中每行只有 4 个数字。

    (如果您遵循关于如何提问的指导原则,例如发布 [mcve],我们可以提供更多帮助)

    贴出的代码提示:

    float a;
    float b;
    float c;
    float d;
    

    并且行上的数字用逗号隔开

    建议:

    #define MAX_LINES 100
    
    float a[ MAX_LINES ];
    float b[ NAX_LINES ];
    float c[ MAX_LINES ];
    float d[ MAX_LINES ];
    
    size_t i = 0;
    while( i<MAX_LINES && 4 == fscanf( fp1, "%lf,%lf,%lf,%lf", &a[i], &b[i], &c[i], &d[i] )
    { 
        // perhaps do something with the most recent line of data
        i++;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-07
      • 2021-11-02
      • 1970-01-01
      • 2015-01-05
      • 1970-01-01
      • 2023-04-05
      相关资源
      最近更新 更多