【问题标题】:Copy double data from a text file into an array in C将文本文件中的双精度数据复制到 C 中的数组中
【发布时间】:2019-05-02 13:09:03
【问题描述】:

我有一个这样的 257 点的文本文件

3.78135
2.84681
2.81403
2.54225
3.10854
  ...

我想读取这些数据并将它们复制到一个数组中。在类似的回答问题的帮助下,我写了这个:

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

int max_read = 258;
double phi[max_read];
FILE *stream;
stream = fopen("namefile.txt", "r");

if (stream == NULL) {
  print ("! Cannot open file %sn", "namefile.txt\n"); 
  exit(1);
} else{
  int m = 0;
  while(m<max_read) {
    phi[m] = // But I still don't know how write the correct value into the array. 
    m++;
  }
}

我也想做这个阅读应对程序直到文件结束。

【问题讨论】:

  • 你知道scanf吗?你知道有一个fscanf 可以从FILE * 读取吗?
  • 不,抱歉,我不知道 :)

标签: c arrays file text double


【解决方案1】:

我认为这应该可以解决问题。

if (stream == NULL) {
    fprint("! Cannot open file %sn", "namefile.txt\n");
    exit(1);
} else{
    int m = 0;
    while (fscanf(stream, "%lf\n", &phi[m])){
        m++;
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-05
    • 2016-06-11
    • 2016-06-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多