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 ","?
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, ",");
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With