Why does strtof always evaluate to HUGE_VAL?

What could be the problem? It doesn’t matter which number I choose for str, it is always 2681561585988519419914804999641169225495873164118478675544712288744352806014709395360374859633380685538006371637297210170750776562389313989286729

char *str = "2.6"; printf("%f\n", strtof(str, (char**)NULL)); //prints 26815615859885194199148049996411692254958731641184786755447122887443528060147093953603748596333806855380063716372972101707507765623893139892867298012168192.00 

whole program:

 #include <stdio.h> #include <string.h> #include <stdlib.h> int main(int argc, char *argv[]) { char *str = "2.6"; printf("%f\n", strtof(str, NULL)); return 1; } 

using -wall:

 test4.c:7: warning: implicit declaration of function âstrtofâ 
+4
source share
5 answers

What platform are you building on? The warning you say is emitted:

 test4.c:7: warning: implicit declaration of function âstrtofâ 

indicates that the compiler does not know that strtof() returns a float, so it will press int on a call to printf() instead of double . strtof() usually declared in stdlib.h , which you include. But this is not a standard feature before C99, so the specific compiler platform (and the settings / options you use) can affect whether it is available or not.

+8
source

strtof defined only on C99. Perhaps the compiler -std=c99 option will be fixed, since by default GCC ( -std=gnu89 ) includes only a few C99 functions.

Another option is to use C89-kosher strtod . In any case, probably the best option in the long run. (When do you need singles, except in exceptional circumstances?)

+4
source

Did you forget to include the correct title?

 #include <stdlib.h> #include <stdio.h> int main() { printf("%f\n", strtof("2.6", NULL)); return 0; } 

gives:

 2.600000 

for me...

+3
source

Given your warnings, you should try adding -std = c99 to get the standard C99 definitions from the header. By default, the return value is assumed to be int, and then will try to convert it to float. Obviously this will be wrong. Alternatively, you can simply provide your own proper declaration for strtof ().

+3
source

As others have said, you need -std = c99. But you can also use strtod (), which is a string to double, and you don't need -std = c99 for that.

I am having problems with strtof () on CentOS 5.5 with glibc 2.5 if I did not use -std = c99, but strtod () worked fine.

+2
source

Source: https://habr.com/ru/post/1311643/


All Articles