cscanfdat-protocol

Read each line of a file using fscanf


I am trying to read each line of a .dat file and store it in a float number. I'm using fscanf. My goal is store these lines to after I raffle.

#include <stdio.h>

int main(void)
{
    char url[]="PREMIOS.dat", nome[20];
    float premio[12];
    FILE *arq;

    arq = fopen(url, "r");
    if (arq == NULL) {
        printf("Error\n");
    } else {
        for(i = 0; i < 12; i++) {
            while((fscanf(arq, "%f\n", &premio[i])) != EOF)
                printf("%.2f\n", premio[i]);
        }
    }
    fclose(arq);
    return 0;
}

The .dat file:

100.00
900.00
600.00
1000.00
0.00
400.00
200.00
800.00
0.01
300.00
500.00
700.00

This code can't storage the numbers for some reason. How can i read these numbers as float, storage and after that raffle?


Solution

  • while (fscanf(arq, "%f\n", &premio[i])) != EOF )
           printf("%.2f\n", premio[i]);
    

    Will continue reading the file line-by-line, till the end of file. In that case, only the value at index 0 of premio is being overwritten each time.

    Instead you should try something along the lines of,

    If ((fscanf(arq, "%f\n", &premio[i])) != EOF )
           printf("%.2f\n", premio[i]);