Boost :: program_options - parsing several command line arguments, where some lines, including spaces and characters

I want to parse a few command line arguments using boost :: program_options. However, some arguments are strings enclosed in double quotes. This is what I have -

void processCommands(int argc, char *argv[]) { std::vector<std::string> createOptions; boost::program_options::options_description desc("Allowed options"); desc.add_options() ("create", boost::program_options::value<std::vector<std::string> >(&createOptions)->multitoken(), "create command") ; 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("create") >= 1) { std::string val1 = createOptions[0]; std::string val2 = createOptions[1]; ... // call some function passing val1, val2. } } 

this works great when i do

 cmdparsing.exe --create arg1 arg2 

But it doesn't work when I do

 cmdparsing.exe --create "this is arg1" "this is arg2" 

from the windows command prompt. For the second option, it is converted to ["this" "is" "arg1" "this" "is" "arg2"] in the createOptions vector. So val1 gets "this" and val2 gets "is" instead of "this is arg1" and "this is arg2" respectively.

How can I use boost :: program_option to make this work?

+6
c ++ boost windows command-line-arguments boost-program-options
source share
3 answers

I fixed it with my own Windows function, which handles command line arguments differently. See CommandLineToArgvW for details . Before passing it to the Commands () process, I modify my argv [] and argc using the method mentioned above. Thank you, Bart van Ingen Schoenau, for your comment.

 #ifdef _WIN32 argv = CommandLineToArgvW(GetCommandLineW(), &argc); if (NULL == argv) { std::wcout << L"CommandLineToArgvw failed" << std::endl; return -1; } #endif 
+2
source share

You can achieve this with positional options :

 positional_options_description pos_desc; pos_desc.add("create", 10); // Force a max of 10. 

Then, when parsing the command line, add this pos_desc :

 using namespace boost::program_options; command_line_parser parser{argc, argv}; parser.options(desc).positional(pos_desc); store(parser.run(), vm); 
0
source share

I would write my own command line parser that went through argv and manually parses the parameters. Thus, you can do whatever you want, be it splitting into " or just splitting into -- in such <

cmdparsing.exe --create1 arg1 --create2 arg2

or

cmdparsing.exe --create \"First Arg\" \"Second Arg\"

By doing this manually, you will save time and properly influence what you are really looking for, rather than fighting with a library that does not do what you want.

(You need \ , otherwise it will be broken, as you already see.

-one
source share

All Articles