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++;
}