1

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

[节]
key="xxx#yyy"

检索密钥,返回“xxx”,这是因为哈希标记似乎被解释为注释的开头,因此该行的其余部分被跳过。不幸的是,我不能用其他字符替换“#”,因为该值是正则表达式。我没有找到引用 hashmark 的方法并且不想这样做,因为它会改变我的正则表达式并使其更加不可读。

有没有办法在不重写ini文件解析器的情况下解决这个问题?谢谢你的帮助。

我检索密钥的代码如下所示:

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);
4

1 回答 1

1

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

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

<-- you are here属性树具有 JSON、Xml、Ini ( ) 和 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;
}
于 2011-07-05T07:23:16.053 回答