[英]const char* not being interpreted correctly by C++ to Excel library
I am trying to use libXl to output text from a C++ program to an Excel file. 我正在尝试使用libXl将文本从C ++程序输出到Excel文件。
The problem is coming with this library function: 这个库函数带来了问题:
bool writeStr(int row, int col, const wchar_t* value, Format* format = 0)
Writes a string into cell with specified format.
将字符串写入指定格式的单元格。 If format equals 0 then format is ignored.
如果format等于0,则忽略format。 String is copied internally and can be destroyed after call this method.
字符串是内部复制的,调用此方法后可以销毁。 Returns false if error occurs.
如果发生错误,则返回false。 Get error info with Book::errorMessage().
使用Book :: errorMessage()获取错误信息。
If I give input as a string literal like "Hello World" it is displayed correctly. 如果我以字符串文字(如“ Hello World”)形式输入,则可以正确显示。 However, if I try to give input as a variable of type const char*, it displays garbage.
但是,如果我尝试将输入作为const char *类型的变量提供,它将显示垃圾。
Following is my code. 以下是我的代码。
MyCompany::company
is a QString
. MyCompany::company
是一个QString
。
const char* companyName = MyCompany::company.toStdString().c_str();
sheet->writeStr(4, 0, companyName, companyFormat);
Can anybody tell me what's going on? 有人可以告诉我怎么回事吗? How can I display a variable string using this library?
如何使用此库显示变量字符串?
Thanks for your help. 谢谢你的帮助。
const char* companyName = MyCompany::company.toStdString().c_str();
The problem here is that the buffer companyName
points to becomes invalid immediately after the end of this statement, as c_str() becomes invalid when the temporary std::string returned by toStdString() is destroyed. 这里的问题是该语句结束后,缓冲区
companyName
指向立即变为无效,因为销毁了toStdString()返回的临时std :: string时c_str()变为无效。 You can solve this by keeping the std::string long enough: 您可以通过将std :: string保持足够长的时间来解决此问题:
const std::string companyName = MyCompany::company.toStdString(); //survives until the end of the block
sheet->writeStr(4, 0, companyName.c_str(), companyFormat);
I'd suggest to not convert via std::string though but convert to some well-defined encoding instead. 我建议虽然不要通过std :: string进行转换,但是要转换为一些定义良好的编码。 For example UTF-8:
例如UTF-8:
const QByteArray companyName = MyCompany::company.toUtf8();
sheet->writeStr(4, 0, companyName.constData(), companyFormat);
(Note that const char* companyName = MyCompany::company.toUtf8().constData()
would have the same problem as your code above). (请注意,
const char* companyName = MyCompany::company.toUtf8().constData()
与上面的代码会有相同的问题)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.