如何将QString转换为char *或者相反

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何将QString转换为char *或者相反相关的知识,希望对你有一定的参考价值。

参考技术A 注:如下方法应该是qt3.0的,一些方法大同小异,请参考qt4的类文档说明。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 followingconst 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)) ;还有其他多种方法:方法一 -----------------------------------------#define G2U(s) ( QTextCodec::codecForName("GBK")->toUnicode(s) )#define U2G(s) ( QTextCodec::codecForName("GBK")->fromUnicode(s) )QString str;QCString cstr;str = G2U("中文输入");cstr = U2G(str);QCString有这样一个重载运算符operator const char * () const可以这样printf("%s\n", (const char*) cstr);或是copy出来char buf[1024];strcpy(buf, (const char*) cstr);方法二 -----------------------------------------如果是中文系统直接用 (const char*) str.toLocal8Bit()例如printf("%s", (const char*) str.toLocal8Bit());str是一个QString方法三 -----------------------------------------char str[64];本回答被提问者采纳

以上是关于如何将QString转换为char *或者相反的主要内容,如果未能解决你的问题,请参考以下文章

QT QString转char*,char*转QString;简单明了,看代码。

如何将 QString 转换为 QString 指针?

字符串怎么转换为unsigned char数组

QT3中怎么实现QString与char*的转换

在Qt中如何将QString转换为const char*

怎么把unsigned char数组转化为字符串类型