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)?
答案 0 :(得分:1)
我的猜测是 string value = "2723022"; // <== any reference id from Reference_id column
String gCmd = "SELECT DISTINCT Reference_id FROM myTable WHERE User_id >'" + value + "'";
SqlDataAdapter Sda = new SqlDataAdapter();
Sda.SelectCommand = new SqlCommand(gCmd, nCon);
DataTable Dt = new DataTable();
Sda.Fill(Dt);
for (int count = 0; count < Dt.Rows.Count; count++)
{
string dCmd = "SELECT User_id FROM dEmo_aCcounts WHERE Reference_id = '" + Dt.Rows[count]["Reference_id"] + "'";
SqlDataAdapter dSda = new SqlDataAdapter();
dSda.SelectCommand = new SqlCommand(dCmd, nCon);
DataTable dDt = new DataTable();
dSda.Fill(dDt);
for (int i = 0; i < dDt.Rows.Count; i++)
{
Response.Write(dDt.Rows[i]["User_id"]);
}
}
是一个字符串,所以jsoncpp拒绝将其转换为double。这是合理的,因为通常将诸如"0.4983"
之类的字符串转换为double是没有意义的。
您需要的是手动将字符串转换为double;在C ++ 11中,它将是stod。
答案 1 :(得分:0)
只需查看来源:https://github.com/oftc/jsoncpp/blob/master/src/lib_json/json_value.cpp#L852
显然只有jsoncpp
int
,uint
,real
,null
和boolean
才能被强制转移到double
。 string
不在列表中。
stackoverflow有很多答案可以解释如何自己进行字符串 - >双重转换。其中之一:C++ string to double conversion
此外还有Value::isConvertibleTo()
,允许您在运行时查找值是否可转换为类型:https://github.com/oftc/jsoncpp/blob/master/src/lib_json/json_value.cpp#L924