从json C++输出获取字段中的奇怪字符
问题描述:
我使用从我的.get(电影)函数接收的json值来获取我的json电影对象中每个键的值。我试图将它输出到fltk GUI中的字段中,该字段需要是const char *类型。但是,我得到了奇怪的字符,而不是我的价值观。这里有一个明显的问题吗?从json C++输出获取字段中的奇怪字符
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)
我在我的函数中只粘贴了相关行。如果需要更多澄清,我很乐意提供。
答
您应该将结果保存在std::string
中,然后在该字符串上调用c_str()
以获取C字符串。如果您将这些调用链接起来并立即保存指针,或者只保存C字符串指向的内存的字符串对象将被清除,您将在代码中调用未定义的行为,这不是您想要的。
即
std::string runtime = result.get("Runtime", "NULL").asString();
runtimeInput->value(runtime.c_str());
答
我明白了。我只需要改变.asCString(); asString()。c_str();
我敢肯定,这样做更有说服力,但正如我所说,我是一个新手。
+0
这只会显示工作,它仍然是未定义的行为。 –
您是否尝试过调试代码?尝试在调试器中逐行执行代码,同时监视变量及其值?什么字符串错了? *他们怎么错了?你期望什么文字,你实际上得到了什么? –
对于#1,当我使用std :: string时,我得到了错误消息,他们必须是类型const char *,所以我改变了它。对于#2,这是因为我只是在学习这一点,并且从文档看,这看起来是该做的事情。 – Kendra
哦,你为什么要显式调用'operator []'作为一个函数?为什么不'结果[ “演员”]'? –