C++ boost::program_options 读取与 getopt_long 兼容的参数

标签 c++ boost boost-program-options getopt-long

我正在开发现有程序的更新。 我正在用 boost::program_options 替换 Posix 的 getopt_long()。 但是我的工作没有按预期进行:我想阅读如下参数:

-server=www.example.com
-c config.txt

我尝试了来自 boost::program_options::command_line_style 的多种可能性,但我找不到可以提供与 getopt_long 相同的行为的组合。

我发现对于参数:

-server=www.example.com

我需要旗帜:

command_line_style::allow_long_disguise | command_line_style::long_allow_adjacent

但我在为以下方面创建标志时遇到问题:

-c config.txt

我发现标志:

command_line_style::allow_short | command_line_style::allow_dash_for_short | command_line_style::short_allow_next

给我几乎我想要的。几乎是因为:

ProgramOptionsParserTest.cpp:107: Failure
Value of: params.config
  Actual: " config.txt"
Expected: expectedParams.config
Which is: "config.txt"

所以在使用 boost::algorithm::trim() 之后它会如我所愿。

所以我的问题是:是否可以处理像 -c 配置.txt 有 boost::program_options 但没有 boost::algorithm::trim()?

编辑 我注意到上面的标志不适用于未注册的参数。我已经注册了选项:

  programOptionsDescription.add_options()
      ("help,h", "display help message")
      ("config,c", value<std::string>(), "use configfile")
      ("server,s", value<std::string>(), "server")
      ("ipport,p", value<uint16_t>(), "server port");

但是当我使用未注册的选项时(是的,我有 basic_command_line_parser::allow_unregistered()):

-calibration=something

我明白了:

the argument ('alibration=something') for option '-config' is invalid

我在版本之后的问题是:如何处理带有 boost::program_options 的 getopt_long 的参数?

最佳答案

如果您使用 boost::program_options , 符号 '=' 是正确解析参数所必需的。如果缺少,它将抛出异常。顺便说一句,boost::property_tree也是解析配置文件的一个很好的选择。 代码:

#include <iostream>
#include <boost/propery_tree.hpp>
#include <boost/propery_tree/ini_parse.hpp>
int main()
{
    string filename("test.conf");
    boost::property_tree::ptree parser;
    boost::property_tree::ini_parser::read_ini(filename, parser);
    const string param_1 = parser.get<string>("DEFAULT.-server");
    const string param_2 = parser.get<string>("DEFAULT.-c");
    cout << param_1 << ' ' << param_2 << endl;
    return 0;
}

“DEFAULT”是配置文件的部分名称。你可以试试。

关于C++ boost::program_options 读取与 getopt_long 兼容的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27636119/

相关文章:

c++ - clang 库的文档

c++ - 抛出异常时不调用析构函数

C++ 使用已经实例化的对象

c++ - 当 const 引用参数绑定(bind)到右值时,它是否保留其 "status"?

c++ - 使用带有 MFC CString 的 boost 字符串算法来检查字符串的结尾

c++ - 无法编译用 Boost::Spirit 库编写的简单解析器

c++ - 配置文件中的多个重复部分

c++ - boost ublas矩阵的线程安全

c++ - 如何使用 Boost.program_options 检测拼写错误?

c++ - 使用 '--' 作为带有 boost::program_options 的选项结束标记