How to identify a typo using Boost.program_options?

I am using boost.program_options library. Consider this simplified case.

po::options_description desc("Usage"); desc.add_options() ("uninstall,u", "uninstall program") ("custom,c", po::wvalue<std::wstring>(), "specify custom action"); po::variables_map vm; po::store(po::parse_command_line(argc, argv, desc), vm); po::notify(vm); 

I want to create an error in a command line like this:

 testprog.exe -u c- action1 

Note. The user made a typo "c-" instead of "-c". But the analyzer understands this as one option -u. How to handle such cases?

+7
source share
3 answers

I want to create an error in a command line like this:

 testprog.exe -u c- action1 

Note. The user made a typo "c-" instead of "-c". But the parser understands this as one option -u. How to handle such cases?

Ask the program_options library not to accept positional arguments and you will get the desired behavior

code and compile:

 macmini:stackoverflow samm$ cat po.cc #include <boost/program_options.hpp> #include <boost/version.hpp> #include <iostream> int main(int argc, char* argv[]) { namespace po = boost::program_options; po::options_description desc("Usage"); desc.add_options() ("uninstall,u", "uninstall program") ("custom,c", po::wvalue<std::wstring>(), "specify custom action") ; po::variables_map vm; po::command_line_parser cmd_line( argc, argv ); cmd_line.options( desc ); cmd_line.positional( po::positional_options_description() ); try { po::store( cmd_line.run(), vm ); po::notify(vm); } catch ( const std::exception& e ) { std::cerr << e.what() << std::endl; return -1; } return 0; } macmini:stackoverflow samm$ g++ po.cc -I /opt/local/include -L/opt/local/lib -lboost_program_options -Wl,-rpath,/opt/local/lib 

mileage:

 macmini:stackoverflow samm$ ./a.out -u c- action1 too many positional options macmini:stackoverflow samm$ ./a.out -u -c action1 macmini:stackoverflow samm$ 
+4
source

Compare argc-1 with the number of arguments found by program_options ? If it does not match, a syntax error occurs.

He will not catch all the cases, but he can catch those important to you.

+2
source

I think the only way to do this is to make sure that every required argument is present, for example, by checking the quantity of each type.

 if (vm.count("uninstall")) { ... } if (vm.count("custom")) { ... } 

You can generate an error if the required parameters are not present (for example, count is 0) or are present (for example, -u and -c cannot be specified, it will be considered as >0 ).

0
source

All Articles