boost property_tree get<std::string>().c_str() 返回错误值

问题描述

专家:

我有一个关于 boost::property_tree::getstd::string() 方法的问题。我用它来获取一个字符串值,但是该字符串实例的 c_str() 返回了错误的值。我可以找到一种解决方法来使我的代码正确运行。但是,我还是想知道为什么!下面是代码输出 首先,我通过加载一个 json 文件来初始化一棵树。

boost::property_tree::ptree root;
boost::property_tree::read_json(filename,root);

然后我得到一个 json 字段并打印它。我会得到一个错误的值。

const char* pName= root.get<std::string>("name").c_str();
std::cout<<"name in char* :" <<pName <<",the length is " << strlen(pName) <<std::endl;

输出为:

name in char* :�"z,长度为4

下面的解决方法可以很好地工作:

const std::string& name= root.get<std::string>("name");
std::cout<<"name in string: " << name.c_str() << ",the length is " << strlen(name.c_str()) <<std::endl;

输出正确:

字符串中的名称:ipd.abcdefj.1.1.com,长度为19

为什么将 get() 的结果值赋给一个局部变量可以解决这个问题?

增强版:1.66

gcc 版本:8.3.1

操作系统:CentOS8

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)