• 18515阅读
  • 8回复

Qstring 转换char*问题! [复制链接]

上一主题 下一主题
离线jy597329
 

只看楼主 倒序阅读 楼主  发表于: 2007-04-19
— 本帖被 XChinux 执行加亮操作(2008-04-09) —
Qstring a;
char *b;
想把a的值付给b,试了几种转换方法,不行,有什么方法QT4中,说仔细点,谢谢!
离线shi19
只看该作者 1楼 发表于: 2007-04-19
方法一:
QString qstr("hello,word");
const char * p = qstr.toLocal8Bit().data();
方法二:
const char *p = qstr.toStdString().data();
转换过来的是常量
离线jy597329

只看该作者 2楼 发表于: 2007-04-19
谢谢
离线matrix_ming

只看该作者 3楼 发表于: 2008-04-09
char*转换为QString呢??????

例如 char * temp,
AString msg;
怎么转呀
离线matrix_ming

只看该作者 4楼 发表于: 2008-04-09
sprintf((char*) recv_buf2,"%s 正在使用本帐号! ",inet_ntoa( *(in_addr*)(&bf[0]) ) );

如上,我怎样将recv_buf2赋值给一个QString对象呢???????
离线cqowen
只看该作者 5楼 发表于: 2008-04-10
char* 转化为QString ,那就直接转吧 QString = char*
离线bingogo
只看该作者 6楼 发表于: 2009-06-15
今天也遇到这样的问题:
下面是GOOGLE到的解决方法。
转载到论坛里,供大家使用。
from : http://www.cppblog.com/Alina-zl/archive/2008/11/19/67323.html


如何将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)) ;
离线wuep
只看该作者 7楼 发表于: 2011-03-28

6楼正解!
网上老多菜鸟没搞明白,误导他人啊,
离线1097174341

只看该作者 8楼 发表于: 2012-07-23
能跟俺说说为什么我的printf()不显示么?
大家好,很高兴见到各位~!
快速回复
限100 字节
 
上一个 下一个