我的代码是这样的:
std::istringstream file("res/date.json");
std::ostringstream tmp;
tmp<<file.rdbuf();
std::string s = tmp.str();
std::cout<<s<<std::endl;
输出为res/date.json
,而我真正想要的是这个json文件的全部内容。
答案 0 :(得分:10)
此
std::istringstream file("res/date.json");
创建一个从字符串file
读取的流(名为"res/date.json"
)。
此
std::ifstream file("res/date.json");
创建一个从名为file
的文件中读取的流(名为res/date.json
)。
看到区别?
答案 1 :(得分:4)
我后来找到了一个很好的解决方案。在parser
中使用fstream
。
std::ifstream ifile("res/test.json");
Json::Reader reader;
Json::Value root;
if (ifile != NULL && reader.parse(ifile, root)) {
const Json::Value arrayDest = root["dest"];
for (unsigned int i = 0; i < arrayDest.size(); i++) {
if (!arrayDest[i].isMember("name"))
continue;
std::string out;
out = arrayDest[i]["name"].asString();
std::cout << out << "\n";
}
}
答案 2 :(得分:0)
我尝试了上面的内容,但问题是他们在C ++ 14中不适用于我:P
我从ifstream incomplete type is not allowed
得到的东西都是两个答案和2 json11 :: Json没有::Reader
或::Value
所以答案2不起作用我也不会为了ppl谁使用这个https://github.com/dropbox/json11就是这样做:
ifstream ifile;
int fsize;
char * inBuf;
ifile.open(file, ifstream::in);
ifile.seekg(0, ios::end);
fsize = (int)ifile.tellg();
ifile.seekg(0, ios::beg);
inBuf = new char[fsize];
ifile.read(inBuf, fsize);
string WINDOW_NAMES = string(inBuf);
ifile.close();
delete[] inBuf;
Json my_json = Json::object { { "detectlist", WINDOW_NAMES } };
while(looping == true) {
for (auto s : Json::array(my_json)) {
//code here.
};
};
注意:这是循环,因为我希望它循环数据。 注意:这肯定会有一些错误,但至少我正确地打开了文件。
答案 3 :(得分:0)
将.json
文件加载到std::string
中并将其写入控制台:
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
int main(int, char**) {
std::ifstream myFile("res/date.json");
std::ostringstream tmp;
tmp << myFile.rdbuf();
std::string s = tmp.str();
std::cout << s << std::endl;
return 0;
}