【问题标题】:Parsing multiple command line arguments in c在c中解析多个命令行参数
【发布时间】:2021-07-27 02:43:36
【问题描述】:

我有一个 test.c 程序,它从标准输入读取不同的参数,并且应该根据给定的参数输出不同的东西。

例如:./test.c -a 1 -b 2 -c 3

所以我希望我可以根据字母去拿某个功能,然后根据数字显示特定的东西。所以一个字母后面总是跟着一个数字。

这是我的代码:

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

    printfile();
    while ((++argv)[0]) {
        if (argv[0][0] == '-') {
            switch (argv[0][1]) {
                case 'a':
                    printf("case a\n"); test1(); break;
                case 'b':
                    printf("case b\n"); test2()); break;    
                case 'c':
                    printf("case c\n"); break;
            }
        }
    }
    return 0;
    
}

这里我的代码只接受每个连字符后跟一个字母。是否可以将它们分开,然后将每个字母与其数字放在一起?

【问题讨论】:

  • PSA:getopt 等工具存在。
  • 你在test2()之后多了一个)
  • 不要调用你的程序test,因为有一个系统实用程序也称为test。它会让你犯与你的程序无关的错误,而且很难意识到。我看到你在调用int ./test 时使用了路径,但你没有说你是否意识到像系统工具一样调用你的程序可能会出现的问题。

标签: c parsing arguments main argv


【解决方案1】:

执行此操作的常用方法是使用 getopt() 库。

但如果您想在代码中显式执行此操作,您可以在 case 中增加 argv 并将下一个参数作为参数处理。

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

    printfile();
    while ((++argv)[0]) {
        if (argv[0][0] == '-') {
            int param;
            switch (argv[0][1]) {
                case 'a':
                    printf("case a\n"); 
                    argv++;
                    if (argv[0][0]) {
                        param = atoi(argv[0]);
                        test1(param);
                    } else {
                        printf("Missing argument");
                        exit(1);
                    }
                    break;
                case 'b':
                    printf("case b\n"); 
                    argv++;
                    if (argv[0][0]) {
                        param = atoi(argv[0]);
                        test2(param);
                    } else {
                        printf("Missing argument");
                        exit(1);
                    }
                    break;
                case 'c':
                    printf("case c\n"); 
                    argv++;
                    if (argv[0][0]) {
                        param = atoi(argv[0]);
                        test3(param);
                    } else {
                        printf("Missing argument");
                        exit(1);
                    }
                    break;
            }
        }
    }
    return 0;
    
}

【讨论】:

    猜你喜欢
    • 2013-03-07
    • 1970-01-01
    • 1970-01-01
    • 2017-08-31
    • 2010-10-26
    相关资源
    最近更新 更多