我已经编写了这个json文件(我把它称为layout.json):
{
"nrows":2,
"ncols":3,
"exit_map": [[0,0,0],[0,0,1]],
"maxCapacity":[[200,100,10],[50,100,40]]
}
数组的值对应于一个单元格。 我想从layout.json文件中解析数组exit_map和maxCapacity的数据。
我在main中使用的代码如下所述:
for (int i = 0; i < object.inputData.nrows; i++) {
for (int j = 0; j < object.inputData.ncols; j++) {
Layout layout ("input/layout.json");
Cell cell(i, j, object.inputData.densityMapVector[i][j], layout.maxCapacityVector, exitmapVector);
当我运行代码时,它会产生分段错误。
有任何想法吗?
提前致谢。
答案 0 :(得分:3)
我强烈建议使用外部库来处理json解析。 就个人而言,我曾使用this one一次,我发现它非常简单干净 只需加入它:
#include <nlohmann/json.hpp>
// for convenience
using json = nlohmann::json;
然后你准备好了。 要从文件流中读取,只需:
std::ifstream i("input/layout.json");
json j = json::parse(i);
您可以像这样访问每个字段:
int n_rows = j["nrows"]
auto exit_map = j["exit_map"]
注意:您需要启用C ++ 11支持(即在gcc中添加-std=c++11
),否则您将无法编译代码