Convert string to double

I am trying to convert a string ( const char* argv[] ) to a double 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

+4
source share
4 answers

Use sscanf (Ref)

 sscanf(argv[i], "%lf", numbers+i); 

or strtod (Ref)

 numbers[i] = strtod(argv[i], NULL); 

By the way

 for(i = 1; i < argc, i += 1) { //-----------------^ should be a semicolon (;) 

->

+9
source

You can use strtod , which is defined in stdlib.h

Theoretically, it should be more efficient that a scanf-family of functions, although I do not think it will be measurable.
+1
source

You did not say in what format const char* can be. Suppose these are text strings, such as "1.23", then sscanf(argv[i], "%lf", &numbers[i-1]) should complete the task.

0
source

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


All Articles