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

Asked

Viewed 224 times

0

In the following excerpt of my code I have to read a function of a txt file and extract its coefficients. When I set the coefficients as integers and read them with %d works correctly, but when placing the coefficients with floating point or even whole and reading with %f or %e the number that is read is a totally random number, as if it were garbage. I would like to know why this.

Reading this 1x1+2x2 this way it works. (nVar is the number of variables that the function is formed, this number is informed by a row 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 1.5x1+2.3x2 or even 1x1+2x2 as follows the variables and their contents 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++;
}

1 answer

1


I can’t seem to reproduce your mistake.

That 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 on the second, it prints:

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

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

Putting the input into 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 way out is exactly the same.

  • But I am reading from a txt file, not directly from the keyboard. With 1.5x1+2.3x2 also wrong, with both %d and %e. Reading an integer as in 1x1+2x2 with %d of right. I would like to know why I cannot with %f or %, and he reads a totally random figure in such cases.

  • Read from a file on it. If Voce post exactly like this your file I can try to understand what’s going on.

  • Problem solved by reading with %lf worked. Anyway thank you so much for your time.

  • Good. Always remember that the scanf differentiates the types with floating point but the printf. not.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.