I am trying to use libXl to output text from a C++ program to an Excel file.
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. String is copied internally and can be destroyed after call this method. Returns false if error occurs. Get error info with Book::errorMessage().
If I give input as a string literal like "Hello World" it is displayed correctly. However, if I try to give input as a variable of type const char*, it displays garbage.
Following is my code. MyCompany::company
is a 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. You can solve this by keeping the std::string long enough:
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. For example 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).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.