0

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.

Kendra
  • 125
  • 2
  • 12
  • Have you tried debugging your code? Tried to step through the code, line by line, in a debugger, while monitoring variables and their values? What strings are wrong? *How* are they wrong? What texts did you expect, and what do you actually get? – Some programmer dude Sep 26 '17 at 07:45
  • For #1, when I was using std::string, I got the error message that they had to be type const char * so I changed it. For #2, it's because I'm just learning this and, from the documentation, it looked like that was the thing to do. – Kendra Sep 26 '17 at 07:45
  • Oh and why are you calling `operator[]` explicitly as a function? Why not e.g. `result["Actors"]`? – Some programmer dude Sep 26 '17 at 07:45
  • I'll change that Like I said, I'm new so I must have misinterpreted the documentation for Json::Value. I'm taking in an array there. – Kendra Sep 26 '17 at 07:49

2 Answers2

1

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());
Hatted Rooster
  • 35,759
  • 6
  • 62
  • 122
0

I got it. I just need to change .asCString(); to asString().c_str();

I'm sure there's a more eloquent way of doing this but, as I said, I'm a newbie.

Kendra
  • 125
  • 2
  • 12