c++ - Boost::Program_options, passing an unknown command line argument -


i using boost::program_options pass configuration files program. in particular use command line overriding of of options. example if register 2 options "opt1" , "opt2" can override default values running program

 myprogram.exe --opt1=option_value_1 --opt2=option_value_2 

all good, happened few times run program mistakenly as

 myprogram.exe --opt1=option_value_1 opt2=option_value_2 

in such case (missing double hyphen) no error thrown. in fact can apparently run myprogram as

 myprogram.exe list of unregistered , unknown values 

and still runs correctly. expect @ least informed unexpected happened. there solution problem?

you should remove allow_unregistered() parse command. command should be

po::store(parse_command_line(argc, argv, desc), vm); 

then exception thrown on unknown options.

http://www.boost.org/doc/libs/1_54_0/doc/html/program_options/howto.html#idp123440592

if want exception/error, if option has no "--" should write parser, this, can you

std::pair<std::string, std::string> fix_option(const std::string& value) {    std::string name = value;    std::string val;    std::string::size_type pos = name.find("=");    if (pos != std::string::npos)    {       val = name.substr(pos + 1);       name = name.substr(0, pos);    }    if (name.substr(0, 2) != "--")    {       throw std::logic_error(std::string("invalid command, no -- in command: ") + name);    }    return std::make_pair(name.substr(2), val); } 

code example

results:

./new --help=j  output: j  ./new help=j  output:  terminate called after throwing instance of 'std::logic_error'   what():  invalid command, no -- in command: 

Comments