Reputation: 18171
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?
Upvotes: 3
Views: 2252
Reputation: 1970
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).
Upvotes: 1
Reputation: 5728
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
.
Upvotes: 1
Reputation: 48467
Using Boost.Optional
:
s = pt.get_optional<std::string>("Section1.value1").get_value_or("default");
// ^^^^^^^^^^^^ ^^^^^^^^ ^^^^^^^
Upvotes: 3