0

可能重复:
getopt_long()——正确的使用方法?

我在我的 C 程序中遇到了 getopt_long 的问题。代码:

const struct option long_options[] = { 
    { "help", 0, NULL, 'h' },
    { "num", 1, NULL, 'n' },
    { NULL, 0, NULL, 0 } 
};  
do {
    next_option = getopt_long(argc, argv, short_options, 
        long_options, NULL);
    switch(next_option) {
        case 'h':
            print_usage(stdout, 0); 
        case 'n':
            printf("num %s\n", optarg);
            break;
        case '?':
            print_usage(stderr, 1); 
            break;
        default:
            abort();
    }   
} while(next_option != -1);

这有效:

./a.out --num 3
num 3

这有效(为什么?!):

./a.out --n 3            
num 3

这不会:

./a.out -n 3  
num (null)

so long 选项有效,short 有两个'-'(为什么?),而 short 选项不起作用(printfprints NULL),这是为什么呢?非常感谢。

4

1 回答 1

5

您还需要传递一个简短的选项字符串,如下所示:

const char *short_options ="hn:";

注意:手段-n接受一个论点。

于 2013-02-04T15:06:02.903 回答