views:

230

answers:

5

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 to test the function, but it always returns a value of 0.0. Does anybody know what I'm doing wrong?

+5  A: 

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!

therefromhere
hmm, why the downvote? I'm pretty sure this is the correct answer. Oh well.
therefromhere
Not quite: it implicitly takes it as returning an int, not 0. But you're asking the same question I would...
Darius Bacon
It implicitly *declares* it as returning int. The definition isn't implicit: it's actually calling the library function, the correct definition with the wrong declaration. Hence looking in the wrong place for the return value — an integer register instead of an FP register.
Potatoswatter
In this case, the returned value is 0.0 because eax is set to zero on entry and the actual value is stored on a floating point register. It could be worse if floating point and integer were stored in the same registers.
jbcreix
@Darius Ah sorry yeah, I meant to type returns int, not 0 - wrote that in a hurry on the way out of the door. Correcting now.
therefromhere
Awesome. I thought this was included in the string.h library, but clearly I was wrong. Thanks a lot.
helixed
+1  A: 

You can use sscanf.

double num;
sscanf("123.0", "%lf", &num);
KennyTM
Unless you're trying to parse multiple items from one string, there's no benefit to using `sscanf` over `strtod`. It's more complicated and has the drawback of making it harder to detect malformed data.
jamesdlin
A: 

You if have to use strtod you can do:

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

you can also use sscanf

double num;    
sscanf("123.0","%lf",&num);
codaddict
-1. You're repeating his code, except not allowing a way to detect errors (that's what the second parameter to strtod is for) and exactly repeating an earlier (though only by 2 minutes) answer.
Roger Pate
+1  A: 

You need to include stdlib.h

dc
+1  A: 

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.

Name