Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct
Differences between QString conversion using .toAscii(), .toAscii().data(), or to toLocal8Bit().data()?
knowNothing last edited by
The title is self-descriptive. Help please.
I am using cpp with QT4.
JvdGlind last edited by
Since I am new I would like some feedback on my answer, but as I understand it from the doc:
toAscii() does a 1 on 1 conversion from string to 8 bit array per character.
toAscii().data() gives a pointer to that byte array, so you can use it like you would a char array in plain C or CPP.
toLocal8Bit().data() converts the string to Ascii used by the area set by the platform locals (or latin if undefined) and then gives a pointer to that byte array.
By default they both do the same as toLatin1().data()
To add to JvdGlind, toAscii and its fellow conversion function returns a temporary QByteArray so calling
@char *foo = myQString.toAscii().data();
Will lead to undefined behavior.
The correct way would be
QByteArray myAsciiByteArray = myQString.toAscii();
char *foo = myAsciiByteArray.data();