Current location - Plastic Surgery and Aesthetics Network - Plastic surgery and beauty - How to realize the conversion between QString and char* in QT3
How to realize the conversion between QString and char* in QT3
Under Qt, strings are all QString, which really provides convenience for developers. Think about all kinds of variable types defined in VC, function parameter types are varied, and new type conversions are often needed this year.

When Qt uses third-party open source libraries again, because the types of libraries are basically standard types, Char* is the most common string type.

How to convert QString into char* under Qt requires QByteArray class, and the description of QByteArray class can be found in Qt help document.

Because char* has a "/0" as a terminator at the end, QString::toLatin 1 () will add "/0" after the string.

The method is as follows:

Qstring string;

char * ch

QByteArray ba = str . tolatin 1();

ch = ba . data();

This completes the conversion from QString to char*. The tested program will run without errors.

Pay attention to the third line, and be sure to add that str.toLatin 1 () can't complete it. Data (), there may be an error.

Supplement: The above method is no problem when QString does not contain Chinese, but it is garbled when QString is converted into char* when it contains Chinese, which can be solved by the following methods:

Method 1:

Add GBK encoding support:

# include & ltQTextCodec & gt

QTextCodec::setCodecForTr(QTextCodec::codecForName(" GBK "));

QTextCodec::setCodecForLocale(QTextCodec::codecForName(" GBK "));

Then change the third behavior above: qbytearrayba = str. toloacl8bit (); ToLoacl8Bit supports Chinese.

Method 2:

First, convert QString to String type in the standard library, and then convert string to char*, as shown below:

STD::string str = filename . tostdstring();

const char * ch = str . c _ str();