10

我的代码是这样的:

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 文件的全部内容。

4

4 回答 4

13

std::istringstream file("res/date.json");

创建一个file从 string 读取的流(名为 )"res/date.json"

std::ifstream file("res/date.json");

创建一个file从名为 的文件中读取的流(名为 )res/date.json

看到不同?

于 2012-12-18T14:50:30.670 回答
4

后来我找到了一个很好的解决方案。使用parserfstream.

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";
    }
}
于 2012-12-19T04:02:40.140 回答
1

将文件加载.json到 anstd::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;
}
于 2019-12-04T14:07:33.457 回答
0

我尝试了上面的东西,但问题是它们在 C++ 14 中对我不起作用:P 我incomplete type is not allowed在两个答案和 2 json11::Json 中都得到了类似 ifstream 的东西 json11::Json 没有 a::Reader或 a::Value所以答案 2 也不起作用对于使用此https://github.com/dropbox/json11的 ppl 来说,要做这样的事情:

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.
    };
};

注意:这是一个循环,因为我希望它循环数据。注意:这肯定会出现一些错误,但至少我像上面那样正确打开了文件。

于 2016-05-06T07:26:36.890 回答