Using getopt_long (C++) how do I code up a long & short option to both require arguments?

若如初见. 提交于 2020-01-12 08:36:29

问题


#include <iostream>
#include <getopt.h>

#define no_argument 0
#define required_argument 1 
#define optional_argument 2


int main(int argc, char * argv[])
{
  std::cout << "Hello" << std::endl;

  const struct option longopts[] =
  {
    {"version",   no_argument,        0, 'v'},
    {"help",      no_argument,        0, 'h'},
    {"stuff",     required_argument,  0, 's'},
    {0,0,0,0},
  };

  int index;
  int iarg=0;

  //turn off getopt error message
  opterr=1; 

  while(iarg != -1)
  {
    iarg = getopt_long(argc, argv, "svh", longopts, &index);

    switch (iarg)
    {
      case 'h':
        std::cout << "You hit help" << std::endl;
        break;

      case 'v':
        std::cout << "You hit version" << std::endl;
        break;

      case 's':
        std::cout << "You hit stuff" << std::endl;
        break;
    }
  }

  std::cout << "GoodBye!" << std::endl;

  return 0; 
}

Output:

./a.out -s
Hello
You hit stuff
GoodBye!

Output:

./a.out --stuff
Hello
./a.out: option `--stuff' requires an argument
GoodBye!

Conflict needing resolved: Both -s & --s should say: ./a.out: option `--stuff' requires an argument when used without proceeding arguments following the command. But only --stuff does? Does anyone know what I'm missing here?

Desired result:

./a.out -s
     Hello
     ./a.out: option `--stuff' requires an argument
      GoodBye!

./a.out --stuff
     Hello
     ./a.out: option `--stuff' requires an argument
     GoodBye!

回答1:


Your getopt_long call specifies "svh" for the short options when it should say "s:vh". The colon tells getopt to require an argument for "s".




回答2:


I'm pretty sure you need to replace "svh" with "s:vh". Per the Linux man page for getopt_long "optstring is a string containing the legitimate option characters. If such a character is followed by a colon, the option requires an argument,".



来源:https://stackoverflow.com/questions/8793020/using-getopt-long-c-how-do-i-code-up-a-long-short-option-to-both-require-a

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!