C++ 为什么我的字符在无缘无故地变化?
详情: 我使用这个github项目将Json转换为对象 使用此json:C++ 为什么我的字符在无缘无故地变化?,c++,json,qt,C++,Json,Qt,详情: 我使用这个github项目将Json转换为对象 使用此json: { "bin": "/home/pablo/milaoserver/compile/Devices01.olk", "temp":"/home/pablo/milaoserver/temporal/", "port": "1234", "name": "lekta", } 通过这两行代码,我创建了两个字符指针: char* bin = configuration["bin"].toS
{
"bin": "/home/pablo/milaoserver/compile/Devices01.olk",
"temp":"/home/pablo/milaoserver/temporal/",
"port": "1234",
"name": "lekta",
}
通过这两行代码,我创建了两个字符指针:
char* bin = configuration["bin"].toString().toLatin1().data();
char* temp = configuration["temp"].toString().toLatin1().data();
调试应用程序我有正确的字符串
然而,当我使用它们时,“bin”字符具体地变为
`hom
有什么想法吗
注释中的解决方案:
问题在于数据的“持久性”
我通过以下方式找到了解决方案:
std::string binAux(configuration["bin"].toString().toLatin1().data());
std::string tempAux(configuration["temp"].toString().toLatin1().data());
char* bin = new char[binAux.size()+1] ;
strcpy(bin, binAux.c_str());
char* temp = new char[tempAux.size()+1] ;
strcpy(temp, tempAux.c_str());
这里的错误是因为临时对象
toString()
创建一个分号后不再可用的临时对象
标准国家:
12.2临时对象[类别临时]
3/[…]临时对象将被销毁,这是计算完整表达式(1.9)的最后一步,该表达式(词汇上)包含创建临时对象的点。即使评估以抛出异常结束,这也是正确的。销毁临时对象的值计算和副作用仅与完整表达式关联,而不与任何特定的子表达式关联
也就是说,当您想要访问它时,您有未定义的行为
这将解决您的问题:
QString str = configuration["bin"].toString().toLatin1();
QByteArray ba = str1.toLatin1();
char *bin = ba.data();
但是您想使用什么char*
?您在C++中,使用<代码> STD::String < /C> >或<代码> qString >:
#include <string>
std::string bin(configuration["bin"].toString().toLatin1().data());
#包括
std::string bin(配置[“bin”].toString().toLatin1().data());
你能试试这样的吗
std::string sbin(configuration["bin"].toString().toLatin1().data());
std::string sTemp(configuration["temp"].toString().toLatin1().data());
toString()
创建一个立即删除的QString
对象,以便释放其中包含的数据。我建议您将数据存储在QString
中,直到您使用该char*bin
您的解决方案可能更短,如下所示:
char* bin = strdup(configuration["bin"].toString().toLatin1().data().c_str());
char* temp = strdup(configuration["temp"].toString().toLatin1().data().c_str());
strdup()
几乎完成了所有操作。是否有可能toString
生成一个临时字符串,该字符串在行结束后不“存在”?temp
的值是否正确?temp是否正确存在。还有垃圾桶。但是,当我“使用”它们时,只有bin改变:如果你使用C++和Qt,你应该使用STD::string或qstring,而不是原始char数组。我试图删除“奇怪”的字符,比如“.'”和'`',但是它不起作用。我想使用char *,因为我正在集成一个C chCub,这需要char *这就是问题所在。强迫改变旧的编码员真的很难。我看过你想象不到的“丑陋的老人守则”:P