如何将命令行参数读入C中的双数组/向量?

时间:2022-12-28 20:44:24

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:

当我在C中运行程序时,我需要能够使用命令行输入几个东西。我将使用如下行的命令运行程序,例如:

./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.

然后我理想地将各种条目存储在单独的变量中。我很难将最后一组逗号分隔的数字,0.0,0.5,1.0,1.5数字存储为名为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.

除了我尝试将值存储在MyVector中的行之外,所有这些工作都有效。

1 个解决方案

#1


3  

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.

0.0,0.5,1.0,1.5是单个字符串。因此,您需要将其标记并检索每个元素,然后使用atof()进行转换。例如,您可以使用strtok()进行标记。

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.

如果你打算使用strtok(),请注意它的缺陷。它修改了它的输入字符串。有关详细信息,请参阅strtok()。

#1


3  

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.

0.0,0.5,1.0,1.5是单个字符串。因此,您需要将其标记并检索每个元素,然后使用atof()进行转换。例如,您可以使用strtok()进行标记。

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.

如果你打算使用strtok(),请注意它的缺陷。它修改了它的输入字符串。有关详细信息,请参阅strtok()。