3

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.

user3716193
  • 476
  • 5
  • 21
  • 2
    You need to iterate over `argv[5]` stopping when you reach a comma and calling `atof(...)` on the previously iterated characters. Rinse and repeat until you reach the end of `argv[5]`. – Jonny Henly Jan 19 '17 at 17:58
  • 2
    I'd recommend using `strtod()` instead of `atof()` if you want verification! In fact, with `strtod()`, you can convert as you go (instead of first finding the next comma), and take advantage of the `end` pointer that it provides. – Tim Čas Jan 19 '17 at 18:09

1 Answers1

4

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.

P.P
  • 117,907
  • 20
  • 175
  • 238
  • Worked perfectly. Thank you. – user3716193 Jan 19 '17 at 18:12
  • Alternatively, using `strtod()` would be better in some respects (leaving the command line argument unmutilated, amongst others). Not a critical issue here, but `strtok()` is a nasty piece of work at times (but `strtok_s()` or `strtok_r()` are useful and usable). – Jonathan Leffler Jan 19 '17 at 20:21