现在的位置: 首页 > 综合 > 正文

QString和char *的转换

2012年09月22日 ⁄ 综合 ⁄ 共 876字 ⁄ 字号 评论关闭

在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相同。

抱歉!评论已关闭.