getopt_long无法正确处理我的参数 [英] getopt_long doesnt handle my arguments right
问题描述
int next_option;
int keep_content =0;
int option_index = 0;
const string short_options = "c::";
const struct option long_options[] =
{
{"config", optional_argument, NULL, 'c'},
{"keep", no_argument, &keep_content, 1},
{ NULL,0, NULL, 0}
};
while((next_option = getopt_long(argc,argv,short_options.c_str(),long_options,&option_index))!= -1)
{
cout << "name: " << long_options[option_index].name << " " << "value: " << optarg << endl;
cout << "keep_content: " << keep_content << endl;
}
我在上面的代码中尝试测试参数并切换解析.进行了以下测试:
I have the above code where iam trying to test argument and switch parsing. The following test were made:
a.out -chey --> name: config value: hey //which is correct
a.out -c hey --> name: value: //what's wrong?
a.out --confighey --> name: value: //what's wrong?
a.out --config hey --> name: value: //what's wrong?
a.out -chey --keep --> name: config value: hey keep_content: 0 // what's wrong? keep_content should be 1
能否请您帮我了解正确的用法?我在做什么错了?
can you please help me understand the correct usage? what am i doing wrong?
谢谢您的时间
推荐答案
您期望有一个可选参数,并根据man 3 getopt
:
You are expecting an optional argument and according to man 3 getopt
:
optstring是包含合法选项字符的字符串.如果此类字符后接冒号,则该选项需要一个参数,因此getopt()会放置一个 指向同一argv-element中以下文本的指针,或optarg中以下argv-element文本的指针. 两个冒号表示一个选项带有一个可选的arg;如果有 当前argv元素中的文本(即与选项名称本身相同的词,例如"-oarg"),然后以optarg返回,否则optarg设置为零. 这是一个GNU扩展.如果optstring包含W后跟一个分号,则-W foo被视为long选项--foo. (-W选项由POSIX.2保留用于 实施扩展.)
optstring is a string containing the legitimate option characters. If such a character is followed by a colon, the option requires an argument, so getopt() places a pointer to the following text in the same argv-element, or the text of the following argv-element, in optarg. Two colons mean an option takes an optional arg; if there is text in the current argv-element (i.e., in the same word as the option name itself, for example, "-oarg"), then it is returned in optarg, otherwise optarg is set to zero. This is a GNU extension. If optstring contains W followed by a semicolon, then -W foo is treated as the long option --foo. (The -W option is reserved by POSIX.2 for implementation extensions.)
这篇关于getopt_long无法正确处理我的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!