【问题标题】:How to read data from file with fscanf in c-language如何在 c 语言中使用 fscanf 从文件中读取数据
【发布时间】:2021-12-31 15:59:08
【问题描述】:

我想用“fscanf”导入数字(总共 40000,以空格分隔)(格式:2.000000000000000000e+02)并将其放入一维数组中。我尝试了很多东西,但得到的数字很奇怪。

到目前为止我所拥有的:

int main() {
        FILE* pixel = fopen("/Users/xy/sample.txt", "r");
        float arr[40000];
        fscanf(pixel,"%f", arr);
   
        for(int i = 0; i<40000; i++)
            printf("%f", arr[i]);
}

我希望有人可以帮助我,我是初学者 ;-) 非常感谢!!

【问题讨论】:

  • @JardelLucca 恐怕有些观察家可能认为答案太明显了,甚至不应该问这个问题。
  • @SteveSummit,感谢您的澄清。这是有道理的,尽管我不同意他们的观点。

标签: arrays c scanf


【解决方案1】:

代替:

fscanf(pixel,"%f", arr);

与此完全等价,并且只读取一个值:

fscanf(pixel,"%f", &arr[0]);

你想要这个:

for(int i = 0; i<40000; i++)
   fscanf(pixel,"%f", &arr[i]);

完整代码:

#include <stdio.h>
#include <stdlib.h>

int main() {
  FILE* pixel = fopen("/Users/xy/sample.txt", "r");
  if (pixel == NULL)   // check if file could be opened
  {
    printf("Can't open file");
    exit(1);
  }

  float arr[40000];
  int nbofvaluesread = 0;

  for(int i = 0; i < 40000; i++)  // read 40000 values
  {
     if (fscanf(pixel,"%f", &arr[i]) != 1)
       break;     // stop loop if nothing could be read or because there
                  // are less than 40000 values in the file, or some 
                  // other rubbish is in the file
     nbofvaluesread++;
  } 
  
  for(int i = 0; i < nbofvaluesread ; i++)
     printf("%f", arr[i]);

  fclose(pixel);  // don't forget to close the file
}

免责声明:这是未经测试的代码,但它应该让您了解自己做错了什么。

【讨论】:

  • 应该是&amp;arr[i]
  • @Barmar 错字,感谢编辑。
  • 加一个用于检查scanf 的返回值并在失败的早期跳出循环。
【解决方案2】:

您需要循环调用fscanf()。你只是在读一个数字。

int main() {
    FILE* pixel = fopen("/Users/xy/sample.txt", "r");
    if (!pixel) {
        printf("Unable to open file\n");
        exit(1);
    }

    float arr[40000];
    for (int i = 0; i < 40000; i++) {
        fscanf(pixel, "%f", &arr[i]);
    }

    for(int i = 0; i<40000; i++) {
        printf("%f", arr[i]);
    }
    printf("\n");
}

【讨论】:

    猜你喜欢
    • 2020-03-30
    • 2013-05-06
    • 1970-01-01
    • 1970-01-01
    • 2011-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多