我需要将浮点 csv 转换为 c 中的二维数组。已经看到一篇文章( Import CSV elements into a 2D array in C )解释了到整数数组的转换。任何人都可以帮助修改此代码或我可以用来将 csv 转换为浮点二维数组的新方法
例如:我的csv包含像0.018869,0.015863,0.044758,0.027318,0.049394,0.040823,.....这样的值,并且是4400*500值的csv。所以我需要使用一个大小为 4400*500 的大数组来包含所有这些值。
提前致谢
最佳答案
使用 atof() 将字符串转换为 float 。 Here如果您想阅读它,这是一个链接
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//counters
int i = 0;
int j = 0;
int k = 0;
char c = 0; //for storing a char at a time
char result_char_array[4] = {0}; //float is a 32 bit number, so 4 bytes
FILE *filep; //pointer to file structure
float results[100] = {0}; //to store the float
int main(void)
{
filep = fopen("C:/Documents/test.csv", "r"); //open file , read only
if (!filep)
{
fprintf (stderr, "failed to open file for reading\n");
return -1; //return negative number so you know something went wrong
}
c = fgetc(filep); //get first character
while(c != EOF)
{
if((c == ',') || (c == '\n')) //we want to stop at each comma or newline
{
//i = 0; //reset the count
results[j] = atof(result_char_array); //this converts a string to a float
j++; //increment j
memset(&result_char_array, 0, sizeof(result_char_array)); //clear the array
}
else
{
strncat(&result_char_array, &c, 1);
}
c = fgetc(filep); //get next character
i++;
}
results[j] = atof(result_char_array); //convert last number
fclose (filep); //always close the file
for(k = 0; k <= j; k++)
{
printf("Number %d is: %f\n",k, results[k]); //loop through the results and print line by line
}
getchar();
return 1;
}
关于在c中将浮点csv转换为二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39754635/