Error reading% f and% e of a file in C

0

In the following snippet of my code I have to read a function from a txt file and extract its coefficients. When I put the coefficients as integers and reading them with %d works correctly, but when putting the coefficients with floating point or even integer and reading with %f or %e the number that is read is a totally random number, like it was rubbish. I would like to know why.

Reading this 1x1+2x2 as follows works. (% is the number of variables that the function is formed, this number is informed by a line of the file)

while(indice < nVar)
{                           
    fscanf(fp,"%d",&i);
    c1 = fgetc(fp);
    c2 = fgetc(fp);
    printf("%d%c%c; ",i,c1,c2);
    indice++;
}

but reading the function nVar or even 1.5x1+2.3x2 as follows the variables and their indexes are read correctly, but for the coefficients a random number as garbage is read

while(indice < nVar)
{                           
    fscanf(fp,"%f",&x);
    c1 = fgetc(fp);
    c2 = fgetc(fp);
    printf("%f%c%c; ",x,c1,c2);
    indice++;
}
    
asked by anonymous 10.07.2014 / 04:11

1 answer

1

I can not reproduce your error.

This code

#include <stdio.h>

int main() {
    /* int i; */
    float x;
    char c1, c2;
    int ind = 0;
    while (ind < 2) {
        /* fscanf(stdin,"%d",&i); */
        fscanf(stdin,"%f",&x);
        c1 = fgetc(stdin);
        c2 = fgetc(stdin);
        printf("%f%c%c; ",x,c1,c2);
        ++ind;
    }
    return 0;
}

When I pass as input 1x1 + 2x2 prints:

➜ / tmp ./a.out
1x1 + 2x2 1.000000x1; 2.000000x2; %

Already when I take the comment from the first fscanf and comment the second, it prints:

➜ / tmp ./a.out
1x1 + 2x2 1x1; 2x2; %

If you can give me a different input example I can try to better understand the problem. :

Placing the entry in a file:

#include <stdio.h>

int main() {
    int i;
    char c1, c2;
    int ind = 0;
    float x;
    FILE *f = fopen("test.txt", "r");
    while (ind < 2) {
        /* fscanf(f,"%d",&i); */
        fscanf(f,"%f",&x);
        c1 = fgetc(f);
        c2 = fgetc(f);
        printf("%f%c%c; ",x,c1,c2);
        ++ind;
    }
    fclose(f);
    return 0;
}

The output is exactly the same.

    
10.07.2014 / 04:26