在C++中使用getopt时打印默认参数


static struct option long_options[] =
{
{"r",   required_argument,  0, 'r'},
{"help",        no_argument,        0, 'h'},
{0, 0, 0, 0}
};

int option_index = 0;
char c;
while((c = getopt_long(argc, argv, "r:h", long_options, &option_index)) != -1)
{
switch(c)
{
case 'r':
break;
case 'h':
return EXIT_SUCCESS;
}
}

如何使 h 成为默认参数,因此如果该程序在没有任何参数的情况下运行,就好像它是用 -h 运行的一样?

也许可以尝试这样的事情:

static struct option long_options[] =
{
{"r",    required_argument,  0, 'r'},
{"help", no_argument,        0, 'h'},
{0, 0, 0, 0}
};
int option_index = 0;
char c = getopt_long(argc, argv, "r:h", long_options, &option_index);
if (c == -1)
{
// display help...
return EXIT_SUCCESS;
}
do
{
switch(c)
{
case 'r':
break;
case 'h':
{
// display help...
return EXIT_SUCCESS;
}
}
c = getopt_long(argc, argv, "r:h", long_options, &option_index);
}
while (c != -1);

或者这个:

static struct option long_options[] =
{
{"r",    required_argument,  0, 'r'},
{"help", no_argument,        0, 'h'},
{0, 0, 0, 0}
};
int option_index = 0;
char c = getopt_long(argc, argv, "r:h", long_options, &option_index);
if (c == -1)
c = 'h';
do
{
switch(c)
{
case 'r':
break;
case 'h':
{
// display help...
return EXIT_SUCCESS;
}
}
c = getopt_long(argc, argv, "r:h", long_options, &option_index);
}
while (c != -1);

为什么不创建一个printUsage函数并做类似的事情。

if (c == 0) {
printUsage();
exit(-1);
}

最新更新