tfl*_*tre 5 c++ options getopt
在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;
}
Run Code Online (Sandbox Code Playgroud)
我用这个命令编译它(gcc版本4.1.2 20080704 Red Hat 4.1.2-46):
g++ -Wall test.cpp
Run Code Online (Sandbox Code Playgroud)
它告诉我这个:
test.cpp:44:10: warning: character constant too long for its type
Run Code Online (Sandbox Code Playgroud)
这是结果:
$ ./a.out -v 2 --param 3
c=118
c=0
option param with arg 3
c=-1
verbose=2 param=0
Run Code Online (Sandbox Code Playgroud)
我试图让它在ideone上工作,但它甚至不认识这个选项-v.
正如trojanfoe在对另一个问题的评论中指出的那样,应该可以使用"long-only"选项,因为GNU tar 会这样做.但是,GNU tar使用argp,我很难理解它的源代码.
有人可以给我一个最小的例子,使用GNU getopt_long()或argp()?
有两个问题:
根据示例代码(您的链接),结构中定义的最终选项必须是{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}
};
Run Code Online (Sandbox Code Playgroud)(更重要的是,)您必须包含实际处理"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;
Run Code Online (Sandbox Code Playgroud)如您所见,我使用strcmp函数来比较字符串; 为此你需要#include <cstring>.顺便说一句,你还需要#include <cstdio>你的使用printf.
有了这些变化,该程序对我来说正常工作(在GCC 4.5.1上测试).
在您的案例陈述中,您正在使用:
case 'param':
Run Code Online (Sandbox Code Playgroud)
这给了你警告,因为编译器期望在那个地方有一个字符.
| 归档时间: |
|
| 查看次数: |
4437 次 |
| 最近记录: |