“QT中QString 转const char*为乱码或为空的问题 ”之解决方案

接着前篇:http://blog.csdn.net/bzhxuexi/article/details/17111903

在前篇中遇到了一个问题,当时没解决,今天终于找到了解决方法,我在网上看到了这样的一段解释,源自于QT Center,是这样的:

rajeshs ask a question:

How can I convert a QString to char* and vice versa ?

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:  

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)) ;


上面代码中的加粗蓝色句子是关键,好多人都知道QString 转 const char*要经过两步:

(1)先通过toLatin1()或toAscii()方法转为QByteArray();

(2)再通过data()或constData()方法

就转换成了const  char *。

    但是,好多人都这样写的代码:

     QString str;

     const char *s = str.toLatin1().data();

或  const char *s =  str.toAscii().data();

这样的话,str.toLatin1()的内容没有存储,就直接调用了data()方法。因此,结果就为空或者乱码。

正确的写法应该是这样的:

----------------------------------------------------------------------

       QString  str;

       QByteArray   aByteArray  =  str.toLatin1();//先把转化为QByteArray的结果存储起来

       const char *s =  aByteArray.data();//再调用data()或constData()

------------------------------------------------------------------------------------

或者:

       QString  str;

       QByteArray   aByteArray  =  str.toAscii();//先把转化为QByteArray的结果存储起来

       const char *s =  aByteArray.data();//再调用data()或constData()

--------------------------------------------------------------------------------------------------------------------

Append:

     今天找到了一个更好的解决方法:

  QString  str;

const char *temStr = str.toLocal8Bit();//(1)

qDebug()<<temStr;//(2)

这样,(2)处打印出来也是乱码,但是,可以这样直接把str.toLocal8Bit()放到你要用到const char *的地方,就可以了,我试了,能正常工作。

刚开始,看到qDebug出来的是乱码,以为不能用,后来发现不影响正常使用。

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值