在c中将浮点csv转换为二维数组

标签 c arrays csv

我需要将浮点 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/

相关文章:

php - 使用 PHP 从 MySQL DB 更改 CSV 格式

regex - 如何使用 linux regex 命令将行乘以范围

在C中将int转换为字符串

c - 使用 Linux 和 C 通过串口发送文件

c - C 同义词库程序中的插入函数无法正常工作

arrays - Solidity 被调用的函数应该是付费的,但它是 View 函数

java - 将 FocusListener 添加到 2D JTextField 数组

python - 在 Python 中处理大量数据

c - 需要展开循环宏

javascript - 在 Javascript 中将对象键从一个对象映射/过滤到一个新对象