c++ - 在使用 nlohmann::json 时使用 std::eof 读取 json 文件
问题描述
我正在尝试从 JSON 文件中读取 while 条件是std::eof
但我得到以下 exption :
在抛出 'nlohmann::detail::parse_error' 的实例后调用终止 what(): [json.exception.parse_error.101] 在第 1 行第 1 列解析错误:解析值时出现语法错误 - 输入意外结束;预期的 '['、'{' 或文字
这是文件:
[{"id":0,"price":0,"qty":0},{"id":1,"price":1,"qty":1}]
这是代码:
#include <iostream>
#include <json.hpp>
#include <fstream>
using json = nlohmann::json;
int main() {
std::ofstream f;
f.open("test.json",std::ios_base::trunc |std::ios_base::out);
json result = json::array();
for(int i =0 ;i < 2 ; i++)
{
json j = {
{"id",i},
{"qty",i},
{"price",i}
};
result.push_back(j);
}
f << result;
f.close();
std::ifstream j;
std::string line;
j.open("test.json",std::ios_base::in);
json ob;
while (!j.eof())
{
j>>ob;
std::cout << ob << "\n";
}
j.close();
return 0;
}
解决方案
推荐阅读
- ios - 如何将 UIImage 转换为 .JPEG 格式并将其发送到服务器?
- php - 有人能告诉我为什么这个简单的 PHP 循环不起作用吗?
- blob - 使用 JS 从 UUID 获取本地 BLOB
- java - 在字符串 "}," 之后添加新行
- git - 为什么 Jenkins 和 Github 不会触发拉取请求?
- node.js - 使用 NodeJs 从自动下载链接请求文件
- go - 树递归 - 如何避免“函数结束时缺少返回”?
- java - JAVA 示例中的嵌套 JSON 对象检索
- android - 在视图寻呼机布局中加载滑翔图像
- arrays - 在嵌套数组 MongoDB 中更新或插入新数据