7

我想使用 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

但是当我这样做时不起作用

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

从 Windows 命令行。对于第二个选项,它被转换为["this" "is" "arg1" "this" "is" "arg2"]createOptions 向量。因此,val1gets"this"val2gets 分别"is"代替了"this is arg1"and "this is arg2"

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

4

2 回答 2

2

我使用本地 Windows 函数修复了它,该函数以不同方式处理命令行参数。有关详细信息,请参阅CommandLineToArgvW。在将它传递给 processCommands() 之前,我正在使用上述方法修改我的 argv[] 和 argc。感谢 Bart van Ingen Schenau 的评论。

#ifdef _WIN32
    argv = CommandLineToArgvW(GetCommandLineW(), &argc);
    if (NULL == argv)
    {
        std::wcout << L"CommandLineToArgvw failed" << std::endl;
        return -1;
    }
#endif
于 2010-11-04T20:57:24.710 回答
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);
于 2017-12-14T05:02:38.740 回答