2

我一直在阅读如何使用getopt_long(),以及如何使用 optlong 来“阅读”多个字符选项。

我需要从终端解析以下条目:

./bomb –n String –cp Integer –i Integer –c Integer –fc String

所以在我使用 getoptlong 之前,我定义了我的短选项和长选项:

 if(argc != 11){
    perror("Error en numero de argumentos \n");
    exit(EXIT_FAILURE);
 }

 const char* const short_options = "n:i:c:";
 static struct option long_options[] = {
    {"cp", 1, NULL, 'a'},
    {"fc", 1, NULL, 'b'},
    {0, 0 , 0, 0}
 };

short_options接受n了一个论点(这就是 the:的用途),对于cand 也是如此i。因此,长选项也应如此(它们也都选择参数)。

    while(opt != -1){

        opt = getopt_long(argc, argv, short_options, long_options, NULL);

        switch (opt){   
           case 'n':
           //print it

           case 'a':
          //print it
         } 
    }

现在的问题是,这段代码在解析时非常有效-c -i-n它进入了它所属的案例并正确打印。我的问题,它不适用于-cpand -fc。而且我真的不知道如何解决这个问题,因为我以前没有使用getopt()过。

提前致谢

4

1 回答 1

2

报价man getopt_long

getopt_long() 函数的工作原理类似getopt(),只是它也接受长选项,以两个破折号开头。

getopt_long_only()is like getopt_long(),但-as well--可以表示一个长选项。

因此,您应该使用--cpand--fc或切换到getopt_long_only.

于 2013-02-01T14:25:42.210 回答