6

我想使用boost :: program_options解析多个命令行参数。但是,一些参数是用双引号括起来的字符串。这就是我 -boost :: program_options - 解析多个命令行参数,其中一些是包括空格和字符的字符串

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

当我做

cmdparsing.exe --create arg1 arg2 

这工作正常但是当我从Windows命令行做

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

工作。对于第二个选项,它将在createOptions向量中转换为["this" "is" "arg1" "this" "is" "arg2"]。因此,val1得到"this"val2得到 "is"而不是"this is arg1""this is arg2"

如何使用boost :: program_option来完成这项工作?

+0

这在Linux上工作。 – 2010-11-04 08:50:13

+2

首先要检查的是操作系统如何为您的程序提供这些选项。如果'cmdparsing.exe --create this是arg1'和'cmdparsing.exe --create“这是arg1”'结果与'argv'数组的内容相同,那么您必须找到一些其他方式来说服您的操作系统引号中的部分需要保持在一起。 – 2010-11-04 13:43:06

回答

-1

我会写我自己的命令行解析器,通过argv去手动解析选项。任何你想要的,无论是在"或仅分裂在这样--被拆分这种方式可以做到,

cmdparsing.exe --create1 arg1 --create2 arg2

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

通过做手工,你将节省时间和适当的暗示你真正想要的东西,而不是去打击一个不做你想做的事情的图书馆。

(您需要\否则将被打破了,你已经看到了。

2

我固定它采用原生的Windows函数处理命令行参数不同,详见CommandLineToArgvW。它传递给前processCommands(),我修改我的argv []和ARGC使用上述方法谢谢巴特车不收Schenau的评论

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

你应该能够positional options来实现这一目标:。

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

然后,当你解析命令行添加此pos_desc

using namespace boost::program_options; 
command_line_parser parser{argc, argv}; 
parser.options(desc).positional(pos_desc); 
store(parser.run(), vm); 
相关问题