【问题标题】:How to move values from a CSV file to a float array?如何将值从 CSV 文件移动到浮点数组?
【发布时间】:2017-09-23 21:21:25
【问题描述】:

我有一个格式如下的.csv 文件:

24.74,2.1944,26.025,7.534,9.317,0.55169 [etc]

我想将浮点值移动到浮点数数组中。

数组看起来像这样:

fValues[0] = 24.74
fValues[1] = 2.1944
fValues[2] = 26.025
fValues[3] = 7.534
fValues[4] = 9.317
[etc]

我有 1000 个号码要处理。

实现这个任务的代码是什么?

这是我得到的最接近的代码:

int main()
{
  FILE *myFile;

  float fValues[10000];
  int n,i = 0;

  myFile = fopen("es2.csv", "r");
  if (myFile == NULL) {
    printf("failed to open file\n");
    return 1;
  }

  while (fscanf(myFile, "%f", &fValues[n++]) != EOF);

  printf("fValues[%d]=%f\n", i, fValues[5]); //index 5 to test a number is there.

  fclose(myFile);
  return 0;
}

另外,当我运行此代码时,我会收到退出代码3221224725

这会是与内存访问相关的问题/堆栈溢出)吗?

我的环境:

  • 崇高文本 3,
  • GCC 编译器,
  • 较新的 windows 笔记本电脑

【问题讨论】:

  • 您的文件中有昏迷。您的程序中没有任何内容可以解释它们。你不能假装他们不在那里。
  • n++ - 嗯。在进入该循环之前,n 是什么?如果您的回答是“我不知道”,那么您同意您的程序,因为它也不知道。你永远不会设置它的初始值。您的程序调用未定义的行为

标签: c arrays file csv


【解决方案1】:

从文件中读取时,您不会跳过文件中的逗号。

fscanf 的第一次调用通过%f 格式说明符读取float。在随后的读取中,文件指针位于第一个逗号处并且不会超过该逗号,因为您仍在尝试读取浮点数。

您需要在循环内添加对fscanf 的单独调用以使用逗号:

while (fscanf(myFile, "%f", &fValues[n++]) == 1) {
  fscanf(myFile, ",");
}

另外,你没有初始化n

int n,i = 0;

当您尝试增加它,从而读取一个未初始化的值时,您调用undefined behavior。像这样初始化它:

int n = 0, i = 0;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-01-07
    • 1970-01-01
    • 2021-07-06
    • 1970-01-01
    • 1970-01-01
    • 2017-03-29
    • 1970-01-01
    相关资源
    最近更新 更多