六狼论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

新浪微博账号登陆

只需一步,快速开始

搜索
查看: 35|回复: 0

CString, QString, char*之间的转换

[复制链接]

升级  61.33%

116

主题

116

主题

116

主题

举人

Rank: 3Rank: 3

积分
384
 楼主| 发表于 2013-1-26 12:38:53 | 显示全部楼层 |阅读模式
 
(节选)如何将QString转换为char *或者相反
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)) ;
 

http://www.cppblog.com/Alina-zl/archive/2008/11/19/67323.html
您需要登录后才可以回帖 登录 | 立即注册 新浪微博账号登陆

本版积分规则

快速回复 返回顶部 返回列表