4

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

casperOne
  • 73,706
  • 19
  • 184
  • 253

4 Answers4

9

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 (;)

-->

kennytm
  • 510,854
  • 105
  • 1,084
  • 1,005
1

Or use atof

http://www.cplusplus.com/reference/clibrary/cstdlib/atof/

LukeN
  • 5,590
  • 1
  • 25
  • 33
1

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.

Isak Savo
  • 34,957
  • 11
  • 60
  • 92
0

You haven't said what format the const char*s might be in. Presuming they're text strings like "1.23", then sscanf(argv[i], "%lf", &numbers[i-1]) ought to do the job.

crazyscot
  • 11,819
  • 2
  • 39
  • 40