开发者

C parsing double from argument strings

开发者 https://www.devze.com 2022-12-19 06:08 出处:网络
I\'m trying to parse an argument value in C and convert the number to a double value.I have: char *stringEnd;

I'm trying to parse an argument value in C and convert the number to a double value. I have:

char *stringEnd; double num = strtod("123.0", &stringEnd);

I used "123.0" just t开发者_StackOverflow中文版o test the function, but it always returns a value of 0.0. Does anybody know what I'm doing wrong?


Are you including the relevant header? ie: #include <stdlib.h>

First though (and you should be doing this all the time anyway), try compiling with all warnings on (-Wall on GCC).

If you get a warning about strtod being undefined, that shows where the problem is coming from.

This is a nasty one, because C will implicitly declare any function it doesn't have a prototype for as returning int!


You can use sscanf.

double num;
sscanf("123.0", "%lf", &num);


You if have to use strtod in order to use:

double num = strtod("123.0", NULL);

you can also use sscanf

double num;    
sscanf("123.0", "%lf", &num);


You need to #include stdlib.h.


In which language is your operating system? I'm not sure how the C function strtod reacts, but I know that the equivalent delphi function takes the settings of the operating system into account. Some languages (french, german, ...) use a "," instead of a "." as decimal separator.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号