我有三个文件-一个json文件、我的项目和测试(main.cpp)
json文件:
{
"points": {
"range": 25,
"step": 0.001
}
}
在文件main.cpp
中,此代码:
#include <iostream>
#include <fstream>
#include <string>
#include <nlohmann/json.hpp>
using std::cout;
using std::endl;
using std::string;
using json = nlohmann::json;
int main()
{
std::ifstream jsonFile("json/settings.json");
json parsedFile = json::parse(jsonFile);
jsonFile.close();
double parsed_number;
printf("string: %snstod return: %fn",
parsedFile["points"]["step"].dump().c_str(),
stod(parsedFile["points"]["step"].dump()));
printf("type: %sn", typeid(stod(parsedFile["points"]["step"].dump())).name());
parsed_number = stod(parsedFile["points"]["step"].dump());
printf("step: %fn", parsed_number);
std::string temporary = "0.001";
parsed_number = stod(temporary);
printf("temporary: %s nstep: %f n", temporary.c_str(), parsed_number);
}
/* outputs:
string: 0.001
stod returns: 0.001000
type: d
step: 0.001000
temporary: 0.001
step: 0.001000
*/
这是正确的答案。
但在我的项目中,相同的代码:
std::ifstream jsonFile(json_filename);
assert(jsonFile.is_open());
json parsedFile = json::parse(jsonFile);
jsonFile.close();
//range = stoi(parsedFile["points"]["range"].dump());
double parsed_number;
printf("string: %snstod returns: %fn",
parsedFile["points"]["step"].dump().c_str(),
stod(parsedFile["points"]["step"].dump()));
printf("type: %sn", typeid(stod(parsedFile["points"]["step"].dump())).name());
parsed_number = stod(parsedFile["points"]["step"].dump());
printf("step: %fn", parsed_number);
std::string temporary = "0.001";
parsed_number = stod(temporary);
printf("temporary: %s nstep: %f n", temporary.c_str(), parsed_number);
/* outputs:
string: 0.001
stod returns: 0,000000
type: d
step: 0,000000
temporary: 0.001
step: 0,000000
*/
也就是说,从我的项目中的字符串"0.001"
中,可以获得数字0
,在测试文件中,可以得到正确的0.001
。
我试着看看stod(parsedFile["points"]["step"].dump())
返回了什么。我还尝试将string
转换为double,您可以自己看到结果。
如果不使用拐杖,我该如何解决这个问题?
C++20标准。
我找不到任何答案。。。
您应该使用库函数get<T>()
从json
对象中提取值,而不是自己使用受当前语言环境影响的std::stod
。
在您的情况下:
double parsed_number = parsedFile["points"]["step"].get<double>();
如果您愿意,还可以创建from_json
重载并直接填充对象:
#include <nlohmann/json.hpp>
#include <fstream>
#include <iostream>
using json = nlohmann::json;
json read_json_file() {
if(std::ifstream jsonFile("json/settings.json"); jsonFile) {
return json::parse(jsonFile);
}
return {};
}
struct points {
int range;
double step;
};
void from_json(const json& j, points& p) {
auto& jpnts = j.at("points");
jpnts.at("range").get_to(p.range);
jpnts.at("step").get_to(p.step);
}
int main() {
auto parsedFile = read_json_file();
auto pnts = parsedFile.get<points>();
std::cout << pnts.range << 'n' << pnts.step << 'n';
}