如何使用getopt_long解析多个参数? [英] How do I use getopt_long to parse multiple arguments?

查看:1409
本文介绍了如何使用getopt_long解析多个参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#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, "s:vh", 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;

        if(optarg)
          std::cout << "Your argument(s): " << optarg << std::endl;

        break;
    }
  }

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

  return 0; 
}

所需输出:

./a.out --stuff someArg1 someArg2

Hello
You hit stuff
Your agument(s): someArg1 someArg2
GoodBye!


推荐答案

getopt 当所有选项参数已处理完毕。 - stuff 被识别为接受参数的选项,在这种情况下 someArg1 someArg2 arg不以 - - ,所以它不是一个选项。默认情况下,这将被置换到 argv 的结尾。在 getopt 返回-1之后,所有非选项参数将位于 argv optind argc-1

getopt returns -1 when all option args have been processed. The --stuff is recognized as an option that takes an argument, in this case someArg1. The someArg2 arg does not start with - or --, so it is not an option. By default, this will be permuted to the end of argv. After getopt returns -1, all non-option args will be in argv from optind to argc-1:

while (iarg != -1) {
    iarg = getopt_long(argc, argv, "s:vh", longopts, &index);
    // ...
}

for (int i = optind; i < argc; i++) {
    cout << "non-option arg: " << argv[i] << std::endl;
}

如果添加单个 - optstring 开始, getopt 将返回1(不是'1')并指向 optarg 到非选项参数:

If you add a single - to the start of optstring, getopt will return 1 (not '1') and point optarg to the non-option parameter:

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

    switch (iarg)
    {
      // ...
      case 1:
        std::cout << "You hit a non-option arg:" << optarg << std::endl;
        break;
    }
}

这篇关于如何使用getopt_long解析多个参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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