问题
There seems to be a problem the way boost::program_options's options_description matching is done.
int main(int argc, char* argv[])
{
boost::program_options::options_description desc("CmdLine utility");
desc.add_options()
("hel", "hel message")
("help", "produce help message")
("helps","helps message")
;
boost::program_options::variables_map vm;
boost::program_options::store(boost::program_options::parse_command_line(argc, argv,desc), vm);
boost::program_options::notify(vm);
if(vm.count("help")) {
std::cout << desc << std::endl;
}
if(vm.count("helps")) {
std::cout << "helps..." << std::endl;
}
if(vm.count("hel")) {
std::cout << "hel..." << std::endl;
}
return 0;
}
Output -
C:\code>cmd.exe --helps
helps...
C:\code>cmd.exe --help
helps...
C:\code>cmd.exe --hel
helps...
The output changes if I change the order in which options are added using add_options()
call. Also it looks like program_options does not do a complete command string matching, so even if you enter a substring of the option, it will consider it as a valid option without doing a complete string comparison. If this is a boost::program_options feature, is there any way to force it to do exact string matching rather than doing it with substring matching ? (I am using Boost version 1.42)
回答1:
By default, program_option has allow_guessing style bit on, so a substring match is sufficient. The behaviour you observe, where an option is matching a prefix of the command line, even when there's a different option that matches fully, is a bug. It's fixed in 1.45.
回答2:
Maybe you called wrongly. You example is fine. Look at the output I got :
[vladimir@asa example]$ ./a.out --help
CmdLine utility:
--hel hel message
--help produce help message
--helps helps message
[vladimir@asa example]$ ./a.out --hel
hel...
[vladimir@asa example]$ ./a.out --helps
helps...
来源:https://stackoverflow.com/questions/4197454/boostprogram-options-does-it-do-an-exact-string-matching-for-command-line-op