3

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?

Piotr Skotnicki
  • 46,953
  • 7
  • 118
  • 160
vico
  • 17,051
  • 45
  • 159
  • 315

3 Answers3

3

Using Boost.Optional:

s = pt.get_optional<std::string>("Section1.value1").get_value_or("default");
//     ^^^^^^^^^^^^                                     ^^^^^^^^  ^^^^^^^
Piotr Skotnicki
  • 46,953
  • 7
  • 118
  • 160
1

You should state which boost library you are referring to in your question. The answer is found in the documentation.

You can use get_optional.

Peter
  • 5,608
  • 1
  • 24
  • 43
1

You are using what the documentation calls the "throwing version" of get(). However, there is also a "default value" version which takes an extra argument -- the default value. As a bonus, the type specification is usually not needed since the type is deduced from the default value.

If the default value is "default" then you simply use

string s=pt.get("Section1.value1", "default");

The other answers mention the use of get_optional(), but this isn't exactly what you want since the value of string s is not optional (even though Section.value1 in the INI file is optional).

Null
  • 1,950
  • 9
  • 30
  • 33