Parsing columns of numbers from a CSV file in C

Asked

Viewed 355 times

3

Hello, Good Night

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

0.001,-9.623
0.098,2.540
1.000,-1.002

And I need to separate them preferably into two vectors, or into a matrix (2 columns by 1300 rows). I tried to replace the commas with blank spaces but did not, 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 also did not see a solution with the same, if someone can clarify how to approach the problem, grateful.

1 answer

2


If each value is separated by a comma, just indicate this in the 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 again what you want, and has a , where there should be ;:

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

Best option than to save the number of lines is to go reading while there are lines. This is easy to change your for by a while on the right condition:

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

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

In the while do run while there are two read values.

See the execution result on my machine:

inserir a descrição da imagem aqui

  • Dear thank you very much, solutions I found were based on Strtok. Strong hug.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.