Search code examples
cfile-iofgets

read each float numbers from text file and skip the rest on C


I been struggling with understanding scanf and how it actually works. I have the following text file:

this    is  a   test    !
25.0    400.0   400.0   0.0     0.0
20.0    200.0  400.0    3.0 4.0
30.0    50  600.0   1 .0    2.0
50.0    400.0  200.0    1 .0    -2.0
40.0    700.0   700.0   -1 .0   -2.0

Basically, the code is supposed to read each line and assign them to an individual array ( array A get the float numbers from the first column, array B gets the floats from the second column, and so on). The only thing I have managed to understand is how to open the file for reading:

FILE *file = fopen( argv[1], "r" );

but I can't figure out how to extract the doubles from lines 1, 2, 3, and 4. I used a conditional statement to skip over line 1 by the way. and I read the rest with the following:

while  (fgets(line, sizeof(line), file))
            {
                    if (count < 1)
                    {
                            //printf("%s", line);
                            count++;
                    }
                    else
                    {
                            printf("%s", line);
                    }

            }

the lines are printing, but again... not sure how to extract each individual number. Help would be appreciated.

Edit: solution picked

Here is the code that I used on this test application. As mentioned in the answers, the text file had some typos that made it harder to scan for data and they need to be edited before running the code. Also, a declaration for "int i = 0" has to be added to work on the array.

while  (fgets(line, sizeof(line), file))
            {
                 if( 5 == sscanf(line, "%f%f%f%f%f", &A[i], &B[i], &C[i], &D[i], &E[i]) ) 
                 {
                     i++;
                 } 
                 else 
                 {
                     printf( "Parse failed\n" );

                 }

            }

Solution

  • Something like this:

    if( 5 == sscanf(line, "%f%f%f%f%f", &A[i], &B[i], &C[i], &D[i], &E[i]) ) {
        /* Do something with values */
    } else {
        printf( "Parse failed\n" );
    }
    

    Where i is incremented for every valid data line.