根据类引用,TixmlText 采用 const char* 值作为输入。 我需要将从文本文件读取的整数数据存储到 xml 中。整数数据存储在 int vector 中, vector 的每个元素在传递给 Tixml 文本函数之前都会转换为 const char*。
const char* intToXmlChar(int num)
{
stringstream abc;
string value;
abc<<num;
value=abc.str();
const char* ret_val = value.c_str();
//char* conv_val = const_cast<char*>(ret_val);
return ret_val;
}
但是当我终于看到生成的 xml 文档时。我在保存数字的元素中得到垃圾值
<timestamp>1�504</timestamp>
我们如何正确存储整数数据?
我已经在tinyxml.h中找到了问题发生的地方
class TiXmlNode : public TiXmlBase
函数
void SetValue(const char * _value) {
printf(" pre ---number--- %s using this \n",_value); //-- if the value is say 18504
value = _value;
printf(" post ---number--- %s using this \n",_value); //-- becomes 1�504 saved in xml
}
其中值相同 class TiXmlNode
是TIXML_STRING value;
- 问题:我错过了什么吗 很简单吗?
- 问题:我怎样才能 正确存储整数数据
编辑: 感谢您的回答 从文档中我错过了一点 使用编译时定义:
TIXML_USE_STL
to compile one version or the other. This can be passed by the compiler, or set as the first line of "tinyxml.h".
Note: If compiling the test code in Linux, setting the environment variable TINYXML_USE_STL=YES/NO will control STL compilation. In the Windows project file, STL and non STL targets are provided. In your project, It's probably easiest to add the line "#define TIXML_USE_STL" as the first line of tinyxml.h.
最佳答案
如果您正在编译具有 STL 支持的 TinyXML(您可能应该这样做),TiXmlText
也有一个 std::string
构造函数。正如 sekmet64 所说,当函数退出时,由 std::string
为 c_str()
分配的内存将被释放,因此您实际上返回了一个指向垃圾的指针。
但是,我强烈建议不要分配您自己的内存。相反,返回一个 std::string (它将为您处理内存):
std::string intToXmlChar(int num)
{
std::stringstream abc;
std::string value;
abc<<num;
return abc.str();
}
然后将其传递到 TiXmlText 构造函数中
TiXmlText node(intToXmlChar(i));
或作为
TiXmlText node(intToXmlChar(i).c_str());
后一种情况是可以的,因为 TiXmlText
将在销毁临时字符串之前获取其拷贝。
一般来说,除非(或直到)绝对必要,否则不要转换为 char*
,对于绝大多数情况,std::string
是一个更安全、更优越的选择。时间。
关于c++ - tinyxml c++ 使用 TiXmlText 存储整数数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5417644/