【问题标题】:boost::program_options - parsing multiple command line arguments where some are strings including spaces and charactersboost::program_options - 解析多个命令行参数,其中一些是字符串,包括空格和字符
【发布时间】:2011-05-04 19:01:13
【问题描述】:

我想使用 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 命令行。对于第二个选项,它在 createOptions 向量中转换为["this" "is" "arg1" "this" "is" "arg2"]。因此,val1 得到 "this"val2 得到 "is" 而不是 "this is arg1""this is arg2" 分别。

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

【问题讨论】:

  • 首先要检查的是操作系统如何为您的程序提供这些选项。如果cmdparsing.exe --create this is arg1cmdparsing.exe --create "this is arg1" 导致argv 数组的内容相同,那么您必须找到其他方法让您的操作系统相信引号中的部分需要保持在一起。

标签: c++ windows boost command-line-arguments boost-program-options


【解决方案1】:

我使用本地 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

【讨论】:

    【解决方案2】:

    您应该可以通过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);
    

    【讨论】:

      猜你喜欢
      • 2016-07-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-02
      • 2020-03-27
      • 2019-02-24
      • 2019-09-04
      相关资源
      最近更新 更多