gpt4 book ai didi

c - 读取 CSV 并存储在 C 中的两个 double 组中

转载 作者:太空宇宙 更新时间:2023-11-04 04:31:11 24 4
gpt4 key购买 nike

我想读取一个包含数据点(即 X 和 Y 位置)的 csv 文件。因此我想读取 CSV 文件并将其存储在两个数组 X 和 Y 中。

我正在尝试以下代码:

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

void readEntireFile(void);

int main(void) {

readEntireFile();

return EXIT_SUCCESS;
}

void readEntireFile(){
int ch;
FILE *fp; // pointer to a file type
fp = fopen("/geometrydata.csv", "r");
ch = getc(fp);
while (ch != EOF){ // keep looping until End Of File
putchar(ch); // print the characters read
ch = getc(fp);
}
fclose(fp);
}

通过这段代码,我得到了文件中的记录,但是我不知道如何将这些记录存储在数组中。

文件中的记录格式如下

-3.5,0.00E+00
-3.289729021,0.00E+00
-3.090472028,0.00E+00

所以我必须将 X 存储为

[-3.5 -3.289729021 -3.09.472028] 

和Y作为

[0.00E+00 0.00E+00 0.00E+00]

最佳答案

对于格式化数据,我推荐fscanf:

double X[NO_OF_LINES], Y[NO_OF_LINES]; /* NO_OF_LINES refers to the no of lines in your csv file */
int i;
for(i = 0; i < NO_OF_LINES && fscanf(fp, "%lf,%lf", &X[i], &Y[i]) == 2; i++);

if(i != NO_OF_LINES)
fprintf(stderr, "ERROR! %d lines could not be read, success in reading %d lines", NO_OF_LINES, i);

for(int j = 0; j < i; j++)
printf("X[%d] = %f, Y[%d] = %f", j, X[j], j, Y[j]);

关于c - 读取 CSV 并存储在 C 中的两个 double 组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36112434/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com