如何将值从CSV文件移动到浮点数组?

时间:2022-04-01 12:41:27

I have a .csv file formatted like this:

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

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

I want to move the float values into a floating point number array.

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

The array would look like this:

数组看起来像这样:

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

I have 1000 numbers to process.

我有1000个号码要处理。

What is the code to achieve this task?

实现此任务的代码是什么?

This is the closest I have gotten with my code:

这是我最接近我的代码:

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;
}

Also, when I run this code I receive exit code 3221224725.

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

Would this be a memory access related issue/stack overflow)?

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

My environment:

  • Sublime Text 3,
  • Sublime Text 3,

  • GCC compiler,
  • Newer windows laptop
  • 较新的Windows笔记本电脑

1 个解决方案

#1


2  

When you read from the file, you're not skipping over the commas in the file.

当您从文件中读取时,您没有跳过文件中的逗号。

The first call to fscanf reads a float via the %f format specifier. On subsequent reads, the file pointer is at the first comma and doesn't go past that because you're still trying to read a floating point number.

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

You need to add a separate call to fscanf inside the loop to consume the comma:

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

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

Also, you're not initializing n:

另外,你没有初始化n:

int n,i = 0;

When you then attempt to increment it, thereby reading an uninitialized value, you invoke undefined behavior. Initialize it like this:

然后,当您尝试递增它,从而读取未初始化的值时,您将调用未定义的行为。像这样初始化它:

int n = 0, i = 0;

#1


2  

When you read from the file, you're not skipping over the commas in the file.

当您从文件中读取时,您没有跳过文件中的逗号。

The first call to fscanf reads a float via the %f format specifier. On subsequent reads, the file pointer is at the first comma and doesn't go past that because you're still trying to read a floating point number.

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

You need to add a separate call to fscanf inside the loop to consume the comma:

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

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

Also, you're not initializing n:

另外,你没有初始化n:

int n,i = 0;

When you then attempt to increment it, thereby reading an uninitialized value, you invoke undefined behavior. Initialize it like this:

然后,当您尝试递增它,从而读取未初始化的值时,您将调用未定义的行为。像这样初始化它:

int n = 0, i = 0;