QString和char *的转换
来源:互联网 发布:python版的rstudio 编辑:程序博客网 时间:2024/06/05 10:56
在Qt开发中,经常毫不犹豫的将QString通过toAscii().data()转换为char *类型,所以才让我浪费了N多时间寻找bug。
案例:
在某个项目中,需要传递一个很长的字符串,但通过toAscii().data()转换得到的char *指针,在运行过程中,该指针经常在某个位置变为乱码,所以字符串就被截断了,让我摸不着头脑好几次。
后来百度了一下,把toAscii().data()改成toLatin1().data(),问题解决了。
在main.cpp中,经常使用以下改变中文编码:
所以,如果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相同。
案例:
在某个项目中,需要传递一个很长的字符串,但通过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相同。
- QString和char *的转换
- QString和char *的相互转换
- QT:QString、QByteArray和char *的转换
- QT:QString、QByteArray和char *的转换
- QT:QString、QByteArray和char *的转换
- QString和char *的相互转换
- char* QByteArray 和 QString之间的转换
- QT:QString、QByteArray和char *的转换
- Qt中QString和char *的转换
- QT:QString、QByteArray和char *的转换。
- [Qt] QString 和 char* 转换
- QString和char *转换
- QString和char*转换方法
- QString unsigned char* 的转换
- QString与char *的转换
- Qt中 QString 和int, char等的“相互”转换
- Qt中 QString 和int, char等的“相互”转换
- Qt中 QString 和int, char等的“相互”转换
- dex2jar apktool 工具的使用
- Flash元标签
- 润乾报表根据浏览器窗体自动缩放
- Solr(2)的实例
- 拆阴招儿:两枚Android病毒应用代码分析
- QString和char *的转换
- shell 中字符串的操作和处理(截取)
- 双系统重新安装xp后,ubuntu选项消失
- WPF数据绑定(二)
- BlueStacks模拟器:多平台上运行Android应用
- Hibernate初级知识学习(3)
- solr(3)整合paoding
- win8下QQ五笔引起记事本未响应,改用极点五笔就可以了
- 条件变量