C++ getopt_long将选项名称视为参数
我使用的是getopt_long read命令行选项。代码:C++ getopt_long将选项名称视为参数,c++,c,linux,getopt,getopt-long,C++,C,Linux,Getopt,Getopt Long,我使用的是getopt_long read命令行选项。代码: #include <getopt.h> #include <stdlib.h> #include <stdio.h> int main(int argc, char *argv[]) { int ch; struct option longopts[] = { {"password", required_argument, NULL, 'p'}, {"
#include <getopt.h>
#include <stdlib.h>
#include <stdio.h>
int
main(int argc, char *argv[])
{
int ch;
struct option longopts[] = {
{"password", required_argument, NULL, 'p'},
{"viewonly", no_argument, NULL, 'v'},
{"help", no_argument, NULL, 'h'},
{NULL, 0, NULL, 0}
};
while ((ch = getopt_long(argc, argv, "p:vh", longopts, NULL)) != -1) {
switch (ch) {
case 'p':
printf("optarg: %x %s\n", optarg, optarg);
break;
case 'v':
printf("viewonly is set\n");
break;
case 'h':
case '?':
default:
fprintf(stderr, "error\n");
exit(EXIT_FAILURE);
}
}
return 0;
}
我觉得这很奇怪,我应该怎么做才能防止getopt_long将选项名称视为参数呢?我会在我的switch语句中检查一些错误,可能会检查密码不能以“-”开头。你不能。相反,您必须在稍后的代码中检测问题,例如在检查密码时,然后告诉用户用户提供了错误的密码。但它也会隐藏viewonly选项,使其无法读取。手动操作是否正确?如果用户提供了错误的密码,您是否会在程序中使用viewonly选项?用户传递了错误的密码或者密码丢失了,就像在你的例子中一样,这应该是一个非常致命的错误,这意味着用户将用希望正确的密码重新运行你的程序,这个问题是没有意义的。您的问题只是一个小测试程序中的问题,就像这里提供的一样。如果您使用C++,那么试试Boost程序选项。它就在这里。但我认为还有其他一些条件需要考虑。为什么getopt_long没有检测到optarg是以“-”开头还是以“-”开头并返回“?”?
optarg: 24992bc4 --viewonly