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); 
相關問題