2011-07-05 37 views
1

我使用boost程序選項從ini文件讀取時遇到了一些麻煩。問題是其含有hashmarks(simplyfied示例)的鍵:在程序選項值(ini文件)中使用哈希標記

[段]
鍵= 「XXX#YYY」

檢索關鍵,因爲hashmark似乎是返回 「XXX」,其是解釋爲註釋的開始,因此該行的其餘部分被跳過。不幸的是,我不能用其他字符替代'#',因爲這個值是一個正則表達式。我沒有找到引用哈希標記的方法,並且不希望這樣做,因爲它會改變我的正則表達式,使其更加難以理解。

有沒有辦法處理這個問題,而不重寫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); 

回答

1

也許現在是時候開始使用Boost Property Tree爲你想辦法克服「我解析程序選項」點這裏,真的。

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

屬性樹有JSON,XML,燕麗(<-- 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; 
} 
+0

聽起來不錯,非常感謝! – raines