QString和char *的轉換

在Qt開發中,經常毫不猶豫的將QString通過toAscii().data()轉換爲char *類型,所以才讓我浪費了N多時間尋找bug。
案例:
在某個項目中,需要傳遞一個很長的字符串,但通過toAscii().data()轉換得到的char *指針,在運行過程中,該指針經常在某個位置變爲亂碼,所以字符串就被截斷了,讓我摸不着頭腦好幾次。
後來百度了一下,把toAscii().data()改成toLatin1().data(),問題解決了。

在main.cpp中,經常使用以下改變中文編碼:

#include <QTextCodec>
QTextCodec::setCodecForCStrings(QTextCodec::codecForLocale());
QTextCodec::setCodecForTr(QTextCodec::codecForLocale());

所以,如果QString中存在中文,就使用toAscii()轉換,如果只存在英文,使用toLatin1()即可。

QT文檔這麼寫着:
QByteArray QString::toAscii () const

Returns an 8-bit representation of the string as a QByteArray.

If a codec has been set using QTextCodec::setCodecForCStrings(), it is used to convert Unicode to 8-bit char; otherwise this function does the same as toLatin1().

Note that, despite the name, this function does not necessarily return an US-ASCII (ANSI X3.4-1986) string and its result may not be US-ASCII compatible.

如果使用setCodecForCStrings函數設置過編碼的話,toAscii會把Unicode轉換爲8位的char類型,否則與toLatin1相同。

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