Converting a string into a double
15,208
Solution 1
Use sscanf
(Ref)
sscanf(argv[i], "%lf", numbers+i);
or strtod
(Ref)
numbers[i] = strtod(argv[i], NULL);
BTW,
for(i = 1; i < argc, i += 1) {
//-----------------^ should be a semicolon (;)
-->
Solution 2
Or use atof
http://www.cplusplus.com/reference/clibrary/cstdlib/atof/
Solution 3
You can use strtod which is defined in stdlib.h
Theoretically, it should be more efficient that the scanf-family of functions although I don't think it'll be measurable.
Author by
Admin
Updated on June 07, 2022Comments
-
Admin almost 2 years
I am trying to convert a string (
const char* argv[]
) to adouble
precision floating point number:int main(const int argc, const char *argv[]) { int i; double numbers[argc - 1]; for(i = 1; i < argc; i += 1) { /* -- Convert each argv into a double and put it in `number` */ } /* ... */ return 0; }
Can anyone help me? Thanks