gpt4 book ai didi

c++ - getopt_long 没有正确处理我的论点

转载 作者:行者123 更新时间:2023-11-28 08:03:22 26 4
gpt4 key购买 nike

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;
}

我在上面的代码中尝试测试参数和切换解析。进行了以下测试:

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

你能帮我理解正确的用法吗?我做错了什么?

谢谢你的时间

最佳答案

您需要一个可选参数,根据 man 3 getopt:

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.)

关于c++ - getopt_long 没有正确处理我的论点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10797731/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com