I'm programming a ptree and at some point I need to put DBL_MAX in (as a default value). I see the right number when I open the generated xml-file.
But when I use ptree.get to get the number an exception is thrown:conversion of data to type "d" failed
Here's my code:
using boost::property_tree::ptree;
ptree pt;
double d=-DBL_MAX;
double d2=-1.797693134862316e+308;
double d3=-1.79769e+308;
cout<<d<<endl;
cout<<d2<<endl;
cout<<d3<<endl;
pt.put<double>("double", d);
write_xml("test.xml", pt);
cout << "totalEndTimeLowerBound: " << pt.get<double>("double")<<endl;
//doesn't work with d and d2, but works with d3
What can cause this error and how can I resolve it?
By default,
ptree
stores its values asstd::string
and convert them usingbasic_stringstream
with precision:This problem appears when it converts
DBL_MAX
tostd::string
because it rounds the number to an invalid value. You can check it with the following code:Using Visual Studio, it prints:
However,
DBL_MAX
is defined as1.7976931348623158e+308
so the printed value is out of limits.There are several workarounds but none is perfect:
DBL_MAX
. For example1.797693134862315e+308
.bad_data
exception and assume that it means default.Reduce the precision of the stored value. You can perform this using the following code: