John S.
John S.

Reputation: 531

jsoncpp: convert string to double

I am trying to take a string, that I know represents a decimal, from a JSON object and assign it to a double in C++.

One would expect that asDouble() does the job, but this is not the case. For example if we have the array ["0.4983", "4387"] sitting in a variable Json::Value arr, doing

double x = arr[0].asDouble()

throws an exception Value is not convertible to double.

What is the recommended way of doing this (in C++ 11)?

Upvotes: 1

Views: 5334

Answers (2)

fukanchik
fukanchik

Reputation: 2865

Just have a look at the source: https://github.com/oftc/jsoncpp/blob/master/src/lib_json/json_value.cpp#L852

Obviously in jsoncpp only int, uint, real, null and boolean could be coerced to double. string is not in the list.

There are many answers here at stackoverflow exmplaining how to do string->double conversion yourself. One of them: C++ string to double conversion

Additionally there is Value::isConvertibleTo() which allows you to find at runtime if a value is convertible to a type: https://github.com/oftc/jsoncpp/blob/master/src/lib_json/json_value.cpp#L924

Upvotes: 0

scinart
scinart

Reputation: 466

My guess is that "0.4983" is a string, so jsoncpp refuses to convert it into a double. This is reasonable since normally to convert a string such as "abc" into a double makes no sense.

What you need is to manually convert the string to double; in C++11 it would be stod.

Upvotes: 2

Related Questions