Search code examples
c++c++11pointersfltkjsoncpp

Getting strange characters in fields with output from json c++


I'm using the json value I receive from my .get(movie) function to get the values of each of the keys within my json movie object. I'm trying to output it into fields in a fltk GUI, which need to be const char * type. However, I'm getting strange characters instead of my values. Is there an obvious issue here?

 Json::Value result = m.get(movie);
 std::cout << result << endl;
 const char *released = result.get("Released", "NULL").asCString();
 releasedInput->value(released);
 const char *rated = result.get("Rated", "NULL").asCString();
 ratedInput->value(rated);
 Json::Value actors = result.operator[]("Actors");
 const char *plot = result.get("Plot", "NULL").asCString();
 plotMLIn->value(plot);
 const char *runtime = result.get("Runtime", "NULL").asCString();
 runtimeInput->value(runtime);
 Json::Value genre = result.operator[]("Genre");
 const char *filename = result.get("Filename", "NULL").asCString();
 filenameInput->value(filename);
 const char *title = result.get("Title", "NULL").asCString();
 titleInput->value(title)

I've pasted only the relevant lines within my function. If more clarification is needed, I'm happy to provide it.


Solution

  • You should save the result in a std::string and then call c_str() on that string to get a C-string. If you chain those calls and save the pointer instantly or only do asCString() the string object holding the memory the C-string is pointing at will have been cleared and you will invoke undefined behavior in your code which is not what you want.

    I.E

    std::string runtime = result.get("Runtime", "NULL").asString();
    runtimeInput->value(runtime.c_str());