gpt4 book ai didi

c++ - 在 C++ 中,如何只使用带有必需参数的长选项?

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:05:24 26 4
gpt4 key购买 nike

在 C++ 程序中,我希望有一个带有必需参数的“long-only”选项。下面是我使用 getopt_long() 的最小示例,但它不起作用:

#include <getopt.h>
#include <cstdlib>
#include <iostream>
using namespace std;

void help (char ** argv)
{
cout << "`" << argv[0] << "` experiments with long options." << endl;
}

void parse_args (int argc, char ** argv, int & verbose, int & param)
{
int c = 0;
while (1)
{
static struct option long_options[] =
{
{"help", no_argument, 0, 'h'},
{"verbose", required_argument, 0, 'v'},
{"param", required_argument, 0, 0}
};
int option_index = 0;
c = getopt_long (argc, argv, "hv:",
long_options, &option_index);
cout << "c=" << c << endl;
if (c == -1)
break;
switch (c)
{
case 0:
if (long_options[option_index].flag != 0)
break;
printf ("option %s", long_options[option_index].name);
if (optarg)
printf (" with arg %s", optarg);
printf ("\n");
break;
case 'h':
help (argv);
exit (0);
case 'v':
verbose = atoi(optarg);
break;
case 'param':
param = atoi(optarg);
break;
case '?':
abort ();
default:
abort ();
}
}
}

int main (int argc, char ** argv)
{
int verbose = 0;
int param = 0;
parse_args (argc, argv, verbose, param);
cout << "verbose=" << verbose << " param=" << param << endl;
return EXIT_SUCCESS;
}

我用这个命令编译它(gcc 版本 4.1.2 20080704 Red Hat 4.1.2-46):

g++ -Wall test.cpp

它告诉我:

test.cpp:44:10: warning: character constant too long for its type

结果如下:

$ ./a.out -v 2 --param 3
c=118
c=0
option param with arg 3
c=-1
verbose=2 param=0

我试图让它在 ideone 上运行但它甚至无法识别选项 -v

正如 trojanfoe 在他的 comments 中指出的那样另一个问题,应该可以使用“long-only”选项,因为 GNU tar 可以做到。但是,GNU tar 使用 argp我很难理解它的 source code .

有人可以给我一个最小的例子吗,用 GNU getopt_long()argp()

最佳答案

有两个问题:

  1. 根据示例代码(您的链接),结构中定义的最终选项必须是 {0,0,0,0} .我建议将定义更改为

    static struct option long_options[] =
    {
    {"help", no_argument, 0, 'h'},
    {"verbose", required_argument, 0, 'v'},
    {"param", required_argument, 0, 0},
    {0,0,0,0}
    };
  2. (更重要的是,)您必须包含实际处理“param”选项的代码。你在 '0' 中这样做案例:

    case 0:
    if (long_options[option_index].flag != 0)
    break;
    if (strcmp(long_options[option_index].name,"param") == 0)
    param = atoi(optarg);
    break;

如您所见,我使用了 strcmp比较字符串的函数;为此你需要 #include <cstring> .对了,你还需要#include <cstdio>供您使用 printf .

有了这些更改,该程序对我来说工作正常(在 GCC 4.5.1 上测试)。

关于c++ - 在 C++ 中,如何只使用带有必需参数的长选项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10213071/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com