在 C++ 中使用 getopt 时打印默认参数
Print default argument when using getopt in C++
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);
}
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);
}