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++;
}
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.
– Talles
Read from a file on it. If Voce post exactly like this your file I can try to understand what’s going on.
– Lucas Virgili
Problem solved by reading with %lf worked. Anyway thank you so much for your time.
– Talles
Good. Always remember that the
scanf
differentiates the types with floating point but theprintf
. not.– Lucas Virgili