简体   繁体   中英

Using boost::property_tree::ptree how to get the value of a specific key

How do I parse all the sections that are present in the file and get the value for each key. That is, I have to parse section1, get the value for key1, key2, key3 . Proceed to section2 get the value for key1, key2 and key3. My .ini file looks something like this.

[SECTION1]
key1=value1
key2=value2
key3=value3
[SECTION2]
key1=value1
key3=value3
key2=value2

so on

Here's an example:

#include <iostream>
#include <string>
#include "boost/property_tree/ini_parser.hpp"


namespace pt = boost::property_tree;


int main() {
  pt::wptree root;

  pt::read_ini("test.ini", root);
  std::wcout << root.get_optional<std::wstring>(L"SECTION1.key2").value() << std::endl;

  return 0;
}

File "test.ini" contains:

[SECTION1]
key1=value1
key2=value2
key3=value3
[SECTION2]
key1=value1
key3=value3
key2=value2

For get all values:

#include <iostream>
#include <string>
#include "boost/property_tree/ini_parser.hpp"


namespace pt = boost::property_tree;


int main() {
  pt::wptree root;

  pt::read_ini("test.ini", root);

  for (auto& child : root) {
    std::wcout << child.first << std::endl;

    for (auto& sub_child : child.second)
      std::wcout << sub_child.second.get_value<std::wstring>() << std::endl;
  }

  return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM