Hugo Hugo - 2 months ago 12
C Question

Store a integer and floating point number from a .dat file in C language

Thanks for your kindly attention. I have a .dat file as the format below:

3 10.9
1 2.1
(empty line)
10 10.05
10 200


For each line, I want to store the first number(integer) into variable a, and store the second float number in variable

int c;
FILE *fp = fopen("supermarket.dat", "r");
while ((c = fgetc(fp)) != EOF) {
int var1;
float var2;
fscanf(fp, "%d%f", &var1, &var2);
printf("%d\n", var1);
printf("%f\n", var2);
}


Now my program cause no error but all the data is wrong. The out in CMD is:

10
0.900000
1
2.10000
10
10.050000
10
200.0000000
10
200.000000


As you can see, some data is wrong, and it didn't print the empty line as 0 0.
The correct output should be:

3
10.9
1
2.1
0
0
10
10.05
10
200

Answer

You're reading your input with 2 "concurrent" routines: fgetc (read a character) and fscanf (read formatted input). The fgetc part consumes the characters in a wrong way.

I suppose you called it because you wanted to check if end of file was reached but that's not the correct way to do it.

Do that instead:

while (1) {
    int var1;
    float var2;
    int nb_toks = fscanf(fp, "%d%f", &var1, &var2);
    if (nb_toks<2) break;
    printf("%d\n", var1);
    printf("%f\n", var2);
}

fscanf returns the number of items successfully read, so when you reach end of file, it returns 1 or 0, which means you can break out of the loop.