C 使用 getopt_long()

标签 c parsing getopt

我一直在阅读如何使用 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(这就是: 的用途),对于ci。 因此,对于多头期权也应该应用同样的方法(它们也都接受参数)。

    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 时非常有效,它会输入它所属的大小写并正确打印。 我的问题是,它不适用于 -cp-fc。我真的不知道如何解决这个问题,因为我之前没有使用过 getopt()

提前致谢

最佳答案

引用 man getopt_long :

The getopt_long() function works like getopt() except that it also accepts long options, started with two dashes.

getopt_long_only() is like getopt_long(), but - as well as -- can indicate a long option.

因此您应该使用--cp--fc,或者切换到getopt_long_only

关于C 使用 getopt_long(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14648039/

相关文章:

c - 它相当于 llvm 中的 size_t

c - 如何在C中获取整数的特定位段?

c# - 解释递归树遍历的最佳 UML 图是什么?

c - Getopt - 需要输入

使用getopt的C程序无法解析url参数

带有 C 模块的 C++ DLL 项目和错误 2732

C陷入无限循环

java - 如何修复超出 START_ARRAY token 错误

c++ - 如何读取 char argv 输入并解析(检查)它的非整数

regex - 如何修复 Perl Getopt::Long 事件未找到错误?