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()?



  • Hello all,

    The title is self-descriptive. Help please.
    I am using cpp with QT4.



  • 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()


  • Lifetime Qt Champion

    Hi,

    To add to JvdGlind, toAscii and its fellow conversion function returns a temporary QByteArray so calling

    @char *foo = myQString.toAscii().data();
    doSomethingWithFoo(foo);@

    Will lead to undefined behavior.

    The correct way would be
    @
    QByteArray myAsciiByteArray = myQString.toAscii();
    char *foo = myAsciiByteArray.data();
    doSomethingWithFoo(foo);@


Log in to reply