user2138149
user2138149

Reputation: 16977

Boost .ini file parser - multiple section name(s)

I am using boost::property_tree to parse ini files.

I want to be able to do something like the following:

data.ini:

[electron]
position=0,0,0
velocity=0,0,0

[proton]
position=1,0,0
velocity=0,0,0

[proton]
position=-1,0,0
velocity=0,0,0

Currently the program runs, and gives this error: duplicate section name Obviously because there are two [proton] sections.

Is there an alternative way to parse a file like this? Should I perhaps be using an xml file?

Upvotes: 1

Views: 2832

Answers (1)

Grigorii Chudnov
Grigorii Chudnov

Reputation: 3112

Here is a simple reader, in case you need it:

XML-file:

<?xml version="1.0" encoding="utf-8"?>
<data>
  <electron>
    <position>0,0,0</position>
    <velocity>0,0,0</velocity>
  </electron>
  <proton>
    <position>1,0,0</position>
    <velocity>0,0,0</velocity>
  </proton>
  <proton>
    <position>-1,0,0</position>
    <velocity>0,0,0</velocity>
  </proton>
</data>

JSON-file:

{
    "electron": {
        "position": "0,0,0",
        "velocity": "0,0,0"
    },
    "proton": {
        "position": "1,0,0",
        "velocity": "0,0,0"
    },
    "proton": {
        "position": "-1,0,0",
        "velocity": "0,0,0"
    }
}

Read XML & JSON proton nodes:

#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/xml_parser.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <algorithm>
#include <iostream>

int main()
{
    // XML
    {
        boost::property_tree::ptree pt;
        boost::property_tree::read_xml("prop_data.xml", pt);

        for(auto& el : pt.get_child("data.proton"))
        {
            std::cout << el.second.data() << std::endl;
        }
    }

    // JSON
    {
        boost::property_tree::ptree pt;
        boost::property_tree::read_json("prop_data.json", pt);

        for(auto& el : pt.get_child("proton"))
        {
            std::cout << el.second.data() << std::endl;
        }
    }

    return 0;
}

EDIT: It is possible to use arrays for JSON, e.g:

...
"position": [-1, 0, 0],
...

And the code to read values of this array:

    for(auto& el : pt.get_child("proton"))
    {
        std::cout << el.first << std::endl;
        for(auto& a : el.second) {
            std::cout << a.second.data() << std::endl;
        }

        std::cout << std::endl;
    }

Here el.second is just a ptree, and you can iterate through it using a for loop.

Upvotes: 3

Related Questions