我需要在c中将浮点csv转换为2D数组。已经看过一篇文章(Import CSV elements into a 2D array in C),它解释了转换为整数数组。可以帮助修改这段代码或者我可以用来将csv转换为浮点2D数组的新方法> 例如:我的csv包含值0.018869,0.015863,0.044758,0.027318,0.049394,0.040823,.....并且是4400 * 500值csv。所以我需要使用一个4400 * 500的大数组来包含所有这些值。
提前致谢
答案 0 :(得分:0)
查看libcsv,这是一个用ANSI C89编写的CSV库。但请注意,libcsv是根据LGPL许可的。
答案 1 :(得分:0)
使用atof()将字符串转换为浮点数。 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;
}