Parsing columns of numbers from a CSV file in C

3

Hello, Good Night

I have a simple .CSV file, containing only two columns, separated by a comma and the new line, as an example:

0.001,-9.623
0.098,2.540
1.000,-1.002

And you need to separate them preferably in two vectors, or in an array (2 columns per 1300 rows). I tried to change the commas by whitespace but did not give, as in the fraction

for(n = 0; n <= AMOSTRAS_LINHAS, n++)
{
    fscanf(amostras, "%f %f", &tempo[n], &tensao[n])
}

The result of printing is always zero for both, I know the problem is in fscanf, but I can no longer see, there is also the possibility of using strtok (), but I did not see a solution with it either, if anyone can elucidate how to approach the problem gratefully.

    
asked by anonymous 19.03.2018 / 02:23

1 answer

2

If each value is separated by a comma, you just have to indicate this in fscanf . Change it to:

fscanf(amostras, "%f,%f", &tempo[n], &tensao[n])
//                  ^--- virgula

Notice however that your for has the end with <= that will run once more than you want, and has a , where it should have ; :

for(n = 0; n <= AMOSTRAS_LINHAS, n++)
//            ^                ^
//            |-- devia ser <  |
//                             |--- devia ser ;  

Best option to save the number of lines is to read while there are lines. This is easy to do if you change your for by while to the correct condition:

FILE* amostras = fopen("amostras.txt", "r");
float tempo, tensao;

while (fscanf(amostras, "%f,%f", &tempo, &tensao) == 2){
    printf("%f %f\n", tempo, tensao);
}

No while execute as long as there are two read values.

See the running result on my machine:

    
19.03.2018 / 02:55