Current location - Plastic Surgery and Aesthetics Network - Plastic surgery and medical aesthetics - How to convert QString to char * or vice versa
How to convert QString to char * or vice versa
Mutual conversion, reference examples are as follows:

1. Convert from QString to char *

To realize the conversion from QString to char *, generally follow the following steps:

The first step is to call the toLatin 1 () method of QString on the QString object to get the Latin 1 value of the string.

Note that the prototype of toLatin 1 () is as follows: q bytearray qstring:: tolatin1() const.

It will return a QByteArray.

Example:

QString qstr = "convert "

QByteArray ba = qstr . tolatin 1();

Secondly, call the data () method on the QByteArray object obtained in the first step to get a pointer to the data stored in the array.

Example:

const char * CSTR = ba . data();

The complete console program is as follows:

int main(int argc,char **argv)

{

QApplication app(argc,argv);

QString qstr = " convert

QByteArray ba = qstr . tolatin 1();

const char * CSTR = ba . data();

printf("cstr: %s ",CSTR); //output display

Return app.exec ();

}

Of course, there are other ways. The basic difference is whether to use toLatin 1 () of QString or toStdString method. QString's toLocal8Bit () method, and the subsequent steps remain unchanged. You can experiment by yourself.

2. convert char* into QString.

The most convenient method is to call the constructor of QString with QLatin 1String object as parameter.

Example:

const char * cstr

QString qstr = QString(qlatin 1 string(CSTR));