You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Getting std::invalid_argument: stream error when following example #429
I'm new to the library, but following the example on the base README:
// read a JSON file
std::ifstream i("file.json");
json j;
i >> j;
I'm getting the following error:
libc++abi.dylib: terminating with uncaught exception of type std::invalid_argument: stream error
Abort trap: 6
My code is as follows:
#include"json.hpp"using json = nlohmann::json;
json json_obj;
std::ifstream input_json("./test/json/TestItems.json");
if (input_json.is_open())
{
while (getline(input_json, line))
{
std::cout << line << std::endl;
}
input_json >> json_obj; // this line seems to cause the exception
input_json.close();
}
else std::cout << "Unable to load file." << std::endl;
I've verified that input_file is ok, since I can iterate through the lines and print them out in the while loop. As soon as I add input_json >> json_obj I get the above exception.
Am I doing something wrong? Haven't been able to find any doc that says this shouldn't work.
Activity
aharbis commentedon Jan 15, 2017
To clarify, I'm using version 2.0.10 of
json.hppand building with C++11.aharbis commentedon Jan 15, 2017
Additionally, this is the contents of
TestItems.json:theodelrieu commentedon Jan 15, 2017
The
input_jsonstream reaches EOF after thegetlineloop, and is in an invalid state, hence the throw.To fix this, you can add those two lines right after the
getline:However there is a better way to parse a stream with this library:
std::ifstream ifs{"test.json"}; auto parsed_json = json::parse(ifs); std::cout << parsed_json.dump() << std::endl;aharbis commentedon Jan 15, 2017
Ah, of course. Thanks for the tip. I went with the
json::parse()method since it appears to be a cleaner approach.nlohmann commentedon Jan 16, 2017
I hope the error messages become clearer when #244 is merged.