使用getopt_long(C ++)如何编写一个long& short选项都需要参数? [英] Using getopt_long (C++) how do I code up a long & short option to both require arguments?

查看:181
本文介绍了使用getopt_long(C ++)如何编写一个long& short选项都需要参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#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; 
}

输出

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

输出

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

需要解决的冲突 --s应该说: ./ a.out:option`--stuff'需要参数,在命令后不使用参数。但只有 - 东西吗?有没有人知道我在这里缺少什么?

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?

所需结果

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

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


推荐答案

您的getopt_long调用为短选项指定svh当它应该说s:vh。冒号告诉getopt要求s的参数。

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".

这篇关于使用getopt_long(C ++)如何编写一个long&amp; short选项都需要参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆