Search code examples
c++boostboost-propertytree

Reading INI file using Boost Property Tree when value section does not exist


I'm using Boost.PropertyTree to read INI file:

read_ini( "myIni.ini", pt );
string s=pt.get<std::string>("Section1.value1");

If section doesn't contain value1 record then Boost raises exception.

How to read INI file in an elegant way and give a default value to s in case Section1.value1 does not exist?


Solution

  • Using Boost.Optional:

    s = pt.get_optional<std::string>("Section1.value1").get_value_or("default");
    //     ^^^^^^^^^^^^                                     ^^^^^^^^  ^^^^^^^