user3716193
user3716193

Reputation: 476

How do I read in command line arguments into a double array/vector in C?

I need to be able to input several things using the command line when I run my program in C. I would run the program using a command like the line below for example:

./programName 1 2.5 A.txt B.txt 0.0,0.5,1.0,1.5

Then I would ideally have the various entries stored in separate variables. I am having difficulty storing the last set of comma separated numbers, the 0.0,0.5,1.0,1.5 numbers, as a vector called MyVector.

Here is an example of what I have tried:

#include <stdio.h>
#include <stdlib.h>
int main (int argc, char *argv[]){

    int x = atoi(argv[1]); // x = 1
    float y = atof(argv[2]); // y = 2.5
    char *AFileName = argv[3]; // AFileName = A.txt
    char *BFileName = argv[4]; // BFileName = B.txt
    double MyVector[4] = atof(argv[5]); // MyVector = [0.0,0.5,1.0,1.5]

    printf("x = %d\n",x);
    printf("y= %f\n",y);
    printf("AFileName= %s\n",HFileName);
    printf("BFileName= %s\n",AFileName);

    for(int i=0;i<4;i++)
    {
        printf("MyVector[%d] = %f\n",i,MyVector[i]);
    }
}

All of these work except for the line where I try and store the values in MyVector.

Upvotes: 3

Views: 1957

Answers (1)

P.P
P.P

Reputation: 121407

This

double MyVector[4] = atof(argv[5]); // MyVector = [0.0,0.5,1.0,1.5]

won't work as you wanted.

0.0,0.5,1.0,1.5 is a single string. So, you need to tokenzing it and retrieve each element and then do the conversion using atof(). You can use strtok() to tokenize for example.

double MyVector[4];
char *p = strtok(argv[5], ",");

size_t i = 0;
while(p && i<4) {
   MyVector[i++] = atof(p);
   p = strtok(NULL, ",");
}

If you are going to use strtok() be aware of its pitfalls. It modifies its input string. See strtok() for details.

Upvotes: 4

Related Questions