分类: C/C++
2013-11-20 09:45:48
官方:
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)) ;
网上版本
char * 与 const char *的转换
char *ch1="hello11";
const char *ch2="hello22";
ch2 = ch1;//不报错,但有警告
ch1 = (char *)ch2;
char 转换为 QString
其实方法有很多中,我用的是:
char a='b';
QString str;
str=QString(a);
QString 转换为 char
方法也用很多中
QString str="abc";
char *ch;
ch = str.toLatin1.data();
QByteArray 转换为 char *
char *ch;//不要定义成ch[n];
QByteArray byte;
ch = byte.data();
char * 转换为 QByteArray
char *ch;
QByteArray byte;
byte = QByteArray(ch);
QString 转换为 QByteArray
QByteArray byte;
QString string;
byte = string.toAscii();
QByteArray 转换为 QString
QByteArray byte;
QString string;
string = QString(byte);
这里再对这俩中类型的输出总结一下:
qDebug()<<"print";
qDebug()<