Reputation: 69
first of all, compiling with flags -Wall, -ansi, -pedantic. no warnings or errors. and no debugging is helping.
basically my code is working fine however returning very weird and unexpected results when I turn a token from a string to a float using strtof()
the section of code below is:
printf("token is %s\n", token);
newstockdata->unitPrice = strtof(token, NULL);
printf("price is %d\n", newstockdata->unitPrice);
newstockdata is allocated to the correct size: unitPrice is a float variable: the first printf statement prints "150.00": the second printf statement prints "0" but after a few iterations it returns a really long consistent number. any help please?
Upvotes: 0
Views: 490
Reputation: 141618
The problem is here, assuming that unitPrice
is a float
:
printf("price is %d\n", newstockdata->unitPrice);
To print a float
you must use the %f
specifier. Otherwise, it is undefined behaviour and anything could happen.
A possible explanation of the changing values you see might be that your system passes floats in a different register to ints. The printf
receiving %d
is looking in a register that is never set, so you are seeing whatever value was left over from some previous operation.
This is actually pretty common, here is an example - %esi
is used for the int
, and %xmm0
is used for the floating-point value.
Upvotes: 4
Reputation: 839
You have to handle overflow cases. After calling strtof()
check errno
for overflow. If you think the values could be very long, you can use double
or long double
.
Upvotes: -1