简体   繁体   English

在C中使用argv和argc解析命令行

[英]Parsing command line using argv and argc in C

I'm trying to figure out how to get commands from the command line and when getting that command perform a certain method. 我试图找出如何从命令行获取命令,以及何时获取该命令执行某种方法。 I can't get the code to recognize the inputted values. 我无法让代码识别输入的值。 Any ideas? 有任何想法吗?

getopts, fgets, or anything of the sort hasn't worked either. getopts,fgets或任何类似的东西都没有用。

int main(int argc, char *argv[]){
int i = 1;

while((argc > 1) && (argv[i] != "d")) {
   switch (argv[i]) {
     case: "a":
       callMethodA(atoi(argv[i+1]));
       break;
     case: "b":
       callMethodB(atoi(argv[i+1]));
       break;
     case: "c":
       callMethodC(atoi(argv[i+1]));
       break;
     default:
       printf("command not recognized");
   }
   argc++
   i+=2;
}

what's suppose to happen is say inputted as: 假设发生的是输入为:

a 3 5 1 b 2 1 c      4

it would call the function callMethodA() with the parameter int of 3 so 它会调用函数callMethodA(),参数int为3,所以

callMethodA(3);
callMethodA(5);
callMethodA(1);
callMethodB(2);
callMethodB(1);
callMethodC(4);

EDIT from suggestion by PureW 编辑来自PureW的建议

int i = 1;

while((argc > 1) && (strcmp(argv[i], "d") != 0)) {
    if(strcmp(argv[i], "a")) callMethodA(atoi(argv[i+1]));
    else if(strcmp(argv[i], "b")) callMethodB(atoi(argv[i+1]));
    else if(strcmp(argv[i], "c")) callMethodC(atoi(argv[i+1]));

    argc++;
    i+=2;
}

no limit is placed on the order of the commands or on the number of values cal 对命令的顺序或值cal的数量没有限制

argv is a vector of char pointers. argv是一个char指针的向量。 So each argv[i] is actually a memory address. 所以每个argv[i]实际上都是一个内存地址。 Doing a regular comparison as argv[1] == "a" will not work since you are comparing memory locations. 由于您要比较内存位置,因此argv[1] == "a"进行常规比较将不起作用。

What you want to do is use strcmp(argv[1], "a") . 你想要做的是使用strcmp(argv[1], "a") http://www.cplusplus.com/reference/cstring/strcmp/ http://www.cplusplus.com/reference/cstring/strcmp/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM