Rory Thoman Rory Thoman - 16 days ago 8
C Question

strtof() producing weird results in C

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?

Answer

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.