How to read a json file into a C++ string

aiziyuer picture aiziyuer · Dec 18, 2012 · Viewed 23.3k times · Source

My code like this:

std::istringstream file("res/date.json");
std::ostringstream tmp;
tmp<<file.rdbuf();
std::string s = tmp.str();
std::cout<<s<<std::endl;

The output is res/date.json, while what I really want is the whole content of this json file.

Answer

Bart van Ingen Schenau picture Bart van Ingen Schenau · Dec 18, 2012

This

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

creates a stream (named file) that reads from the string "res/date.json".

This

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

creates a stream (named file) that reads from the file named res/date.json.

See the difference?