处理特定的命令行参数

时间:2014-03-12 15:29:41

标签: c command-line-arguments

所以我完成了一个项目,我只剩下一件事了;正确处理命令行参数。我以为我已经处理了它们但显然我错了......可以有两组不同的命令行参数,这里是我所谈论的例子:./hw34 -c 385 280 50 balloons.ascii.pgm balloonCircle.pgm./hw34 -e 100 balloons.ascii.pgm balloonEdge.pgm

这是我试图处理这些论点的内容,但这似乎并不奏效: if(argc==5) && isdigit(atoi(argv[2]))){else if(argc==7 && isdigit(atoi(argv[2])) && isdigit(atoi(argv[3])) && isdigit(atoi(argv[4]))){

我坚持的是试图弄清楚argv [x]是不是数字。

3 个答案:

答案 0 :(得分:3)

您应该尝试以不同方式处理命令行。

类似的东西:

  

./ hw34 -c" 385,280,50" balloons.ascii.pgm balloonCircle.pgm

     

./ hw34 -e 100 balloons.ascii.pgm balloonEdge.pgm

然后结合getopt进行命令行处理,strtok进行参数列表的分割,你应该能够达到你想要的效果。

主要优点是您不必再担心参数的数量或它们在命令行中的位置。

答案 1 :(得分:1)

带有参数原型的Canonical main function

int main( int argc, char* argv[] );

argc是参数的数量,char* argv[] - 这些参数的字符串数组。数组的第一个元素 - argv[0] - 是程序的名称。

要检查参数是否为数字,您可以使用strtol函数返回转换状态:

char* tail;
long n = strtol(argv[2], &tail, 10);  // 10 is the base of the conversion

然后在数字(如果有)之后检查指向字符串部分的尾部:

if (tail == argv[2]) { // not a number
   // ...
} else if (*tail != 0) {  // starts with a number but has additional chars
   // ...
} else { // a number, OK
   // ...
}

答案 2 :(得分:1)

argv字符串的数组。没有整数。

您可以使用strtol轻松测试是否可以进行转换,然后检查是否已消耗所有字符:

char const * str = "123";
char * endptr;
long number = strtol(str, &endptr, 0); // do the conversion to long integer
if(&str[strlen(str)] == endptr) // endptr should point at the end of original string
    printf("ok");
else
    printf("error");
相关问题