c++ - 在程序选项值(ini 文件)中使用井号

标签 c++ boost-program-options

我在使用 boost 程序选项读取 ini 文件时遇到了一些问题。问题是包含哈希标记的 key (简单示例):

[节]
key="xxx#yyy"

检索 key ,返回“xxx”,这是因为井号似乎被解释为评论的开始,因此该行的其余部分被跳过。不幸的是,我不能用其他字符替换“#”,因为该值是一个正则表达式。我没有找到引用井号的方法,我宁愿不这样做,因为它会改变我的正则表达式并使它更难读。

有没有一种方法可以在不重写 ini 文件解析器的情况下解决这个问题? 感谢您的帮助。

我检索 key 的代码如下所示:

std::string key;
boost::program_options::options_description opDesc("test");
opDesc.add_options()("section.key", po::value<string>(&key))
std::ifstream ifs("file.ini");
boost::program_options::parse_config_file(ifs, opDesc);

最佳答案

也许是时候开始使用 Boost Property Tree 了因为您已经过了这里的“我正在解析程序选项”这一点,真的。

http://www.boost.org/doc/libs/1_46_1/doc/html/property_tree.html

属性树具有 JSON、Xml、Ini (<-- you are here) 和 INFO 格式的解析器/格式化程序。链接页面在几行中具体指定了哪些往返(大多数往返,JSON 特定类型信息和有时尾随空格除外)。

我想您会喜欢 INI 格式(因为它接近您正在使用的格式)和 INFO 设置(因为除了分层嵌套的部分之外,它还有更多的字符串语法)。


来自样本:

#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/xml_parser.hpp>
#include <boost/foreach.hpp>
#include <string>
#include <set>
#include <exception>
#include <iostream>

struct debug_settings
{
    std::string m_file;               // log filename
    int m_level;                      // debug level
    std::set<std::string> m_modules;  // modules where logging is enabled
    void load(const std::string &filename);
    void save(const std::string &filename);
};

void debug_settings::load(const std::string &filename)
{
    using boost::property_tree::ptree;
    ptree pt;
    read_xml(filename, pt);
    m_file = pt.get<std::string>("debug.filename");
    m_level = pt.get("debug.level", 0);
    BOOST_FOREACH(ptree::value_type &v, pt.get_child("debug.modules"))
        m_modules.insert(v.second.data());
}

void debug_settings::save(const std::string &filename)
{
    using boost::property_tree::ptree;
    ptree pt;
    pt.put("debug.filename", m_file);
    pt.put("debug.level", m_level);
    BOOST_FOREACH(const std::string &name, m_modules)
        pt.add("debug.modules.module", name);
    write_xml(filename, pt);
}

int main()
{
    try
    {
        debug_settings ds;
        ds.load("debug_settings.xml");
        ds.save("debug_settings_out.xml");
        std::cout << "Success\n";
    }
    catch (std::exception &e)
    {
        std::cout << "Error: " << e.what() << "\n";
    }
    return 0;
}

关于c++ - 在程序选项值(ini 文件)中使用井号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6578339/

相关文章:

c++ - 如何在 boost::program_options 中为 vector<string> 指定默认值

c++ - 使用 boost 解析选项

c++ - 使用 Boost::program_options 允许多次出现自定义类型

c++ - 如何在SDL(C++)中绘制正在进行的图像计算?

c++ - 数组声明在 C++ 中如何工作?

c++ - 不能多次指定选项 '--opt'

c++ - vector 值 boost::program_options 的默认值

c++ - 如何以编程方式获取 MSVC 中任何类型的函数的修饰名称

c++ - 动态转换抛出指针不是 std::__non_rtti_object

c++ - 添加静态 constexpr 成员会改变结构/类的内存映射吗?