How to read these mixture of data in C

This program reads from the file and converts the tokens to floats. You should read an entire line and tokenize it. Then you just need to create an array and add to the array at the right place in the code.

#include <stdio.h>
#include <stdlib.h>
#include <memory.h>

int main(void) {
    FILE *sp1;
    char line[256];
    double array[256];
    int i = 0;

    sp1 = fopen("data.txt", "r");
    while (1) {
        if (fgets(line, 150, sp1) == NULL) break;
        char *p = strtok(line, " ");
        while (p != NULL) {
            double fd = atof(p);
            array[i++] = fd;
            p = strtok(NULL, " ");
        }
    }

    for(int j=0;j<i;j++)
        printf("%f\n", array[j]);

    return 0;
}

data.txt

120 5.0000000000000000E-01   -5.0000000000000000E-01  5.0000000000000000E-01
5.0000000000000000E-01   -5.0000000000000000E-01  -5.0000000000000000E-01
5.0000000000000000E-01   -5.0000000000000000E-01  1.6666666666999999E-01
5.0000000000000000E-01   -5.0000000000000000E-01  -1.6666666666999999E-01
-5.0000000000000000E-01

Output

120.000000
0.500000
-0.500000
0.500000
0.500000
-0.500000
-0.500000
0.500000
-0.500000
0.166667
0.500000
-0.500000
-0.166667
-0.500000

Browse More Popular Posts

Leave a Comment