qstring2

最近在寫一個QT程序。需要把QString 轉換成char * 指針。結果遇到程序崩潰的嚴重錯誤。在大量的幫助調試下,發現是QString轉換成char * 的時候,一定要定義一個QBateArray的變量。不能連寫 。
 以下是官方回覆:
How can I convert a QString to char* and vice versa ?(trolltech)
 Answer:
 In order to convert a QString to a char*, then you first need to get a latin1 representation of the string by calling toLatin1() on it which will return a QByteArray. Then call data() on the QByteArray to get a pointer to the data stored in the byte array. See the documentation:
 See the following example for a demonstration:
 
int main(int argc, char **argv)
 {
 QApplication app(argc, argv);
 QString str1 = "Test";
 QByteArray ba = str1.toLatin1();
 const char *c_str2 = ba.data();
printf("str2: %s", c_str2);
 return app.exec();
}
 Note that it is necessary to store the bytearray before you call data() on it, a call like the following
 const char *c_str2 = str2.toLatin1().data();
 will make the application crash as the QByteArray has not been stored and hence no longer exists.

To convert a char* to a QString you can use the QString constructor that takes a QLatin1String, e.g:
 QString string = QString(QLatin1String(c_str2)) ;


本文來自CSDN博客,轉載請標明出處:http://blog.csdn.net/remote_roamer/archive/2010/10/27/5968896.aspx

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章