Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/62.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
getopt无法识别c中的多个命令行标志_C_Command Line Arguments_Getopt - Fatal编程技术网

getopt无法识别c中的多个命令行标志

getopt无法识别c中的多个命令行标志,c,command-line-arguments,getopt,C,Command Line Arguments,Getopt,我正在学习C语言,我正在尝试使用getopt()获取命令行标志。我的问题是,它只会将第一个命令标志识别为标志,并将其他任何标志视为常规命令行参数。这是我的密码: #include <stdio.h> #include <unistd.h> #include <string.h> int main(int argc, char *argv[]) { char *delivery = ""; int thick = 0; int coun

我正在学习C语言,我正在尝试使用getopt()获取命令行标志。我的问题是,它只会将第一个命令标志识别为标志,并将其他任何标志视为常规命令行参数。这是我的密码:

#include <stdio.h>
#include <unistd.h>
#include <string.h>

int main(int argc, char *argv[]) {
    char *delivery = "";
    int thick = 0;
    int count = 0;
    char ch;

    while ((ch = getopt(argc, argv, "d:t")) != -1) {
        switch (ch) {
            case 'd':
                delivery = optarg;
                break;
            case 't':
                thick = 1;
                break;
            default:
                fprintf(stderr, "Unknown option: '%s'\n", optarg);
                return 1;
        }
        argc -= optind;
        argv += optind;
    }
    if(thick) {
        puts("Thick crust.");
    }
    if (delivery[0]) {
        printf("To be delivered %s.\n", delivery);
    }
        puts("Ingredients:");
        for(count = 0; count < argc; count++) {
            if (!strstr(argv[count], "./")) {
                puts(argv[count]);
            }
        }
    return 0;
}
但是,当我执行多个标志时:

$ ./order_pizza -d now -t Anchovies Pineapple
To be delivered now.
Ingredients:
-t
Anchovies
Pineapple

$ ./order_pizza -t -d now Anchovies Pineapple
Thick crust.
Ingredients:
-d
now
Anchovies
Pineapple
我似乎无法找出我做错了什么,因为从我的搜索中,似乎没有人有相同的问题。我在Windows 7上使用cygwin,并使用以下代码行进行编译:

$ gcc order_pizza.c -o order_pizza

有人有什么想法吗?

在调用
getopt
循环中,不要修改
argc
argv
。它使用这些变量来发挥它的魔力,所以改变它们会把事情搞砸

因此,与此相反:

while ((ch = getopt(argc, argv, "d:t")) != -1) {
    switch (ch) {
    ...
    }
    argc -= optind;
    argv += optind;
}
这样做:

while ((ch = getopt(argc, argv, "d:t")) != -1) {
    switch (ch) {
    ...
    }
}
argc -= optind;
argv += optind;

非常感谢你!我觉得自己太笨了,这段代码是我正在使用的书中“填空”练习的一部分,我错过了复制的一些代码(他们没有在我喜欢的地方使用括号,所以当我添加一些括号时,我把结尾的括号放错了位置)。移动支架修复了一切!
while ((ch = getopt(argc, argv, "d:t")) != -1) {
    switch (ch) {
    ...
    }
}
argc -= optind;
argv += optind;