Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert csv string to array of floats

Tags:

c

Can anyone advise on a simple way of converting a csv string to an array of floats in C?

e.g.

char my_string[] = "1.0,2.0,3.0";

to:

my_array = [1.0, 2.0, 3.0]

where my_array is of type float[]

I would use sscanf as a quick and easy solution but I don't know how many values are contained in the string in advance

Is there some existing library function that could do this without me having to resort to looping over every char looking for a ","?

like image 695
bph Avatar asked Dec 12 '22 00:12

bph


2 Answers

You could use strtok():

float my_array[N]; // if you don't know how many there are, use the heap
int i = 0;

char *tok = strtok(my_string, ",");
while (tok != NULL) {
    my_array[i++] = atof(tok);
    tok = strtok(NULL, ",");
}   
like image 163
rid Avatar answered Dec 27 '22 08:12

rid


There's a library you could use - LibCSV

From their description:

libcsv is a small, simple and fast CSV library written in pure ANSI C89 that can read and write CSV data. It provides a straight-forward interface using callback functions to handle parsed fields and rows and can parse improperly formatted CSV files

like image 38
Indy9000 Avatar answered Dec 27 '22 06:12

Indy9000