Qt Forum

    • Login
    • Search
    • Categories
    • Recent
    • Tags
    • Popular
    • Users
    • Groups
    • Search
    • Unsolved

    Differences between QString conversion using .toAscii(), .toAscii().data(), or to toLocal8Bit().data()?

    Language Bindings
    3
    3
    4708
    Loading More Posts
    • Oldest to Newest
    • Newest to Oldest
    • Most Votes
    Reply
    • Reply as topic
    Log in to reply
    This topic has been deleted. Only users with topic management privileges can see it.
    • K
      knowNothing last edited by

      Hello all,

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

      1 Reply Last reply Reply Quote 0
      • J
        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()

        Jeffrey VAN DE GLIND
        Principle Consultant @ Nalys
        www.nalys-group.com

        1 Reply Last reply Reply Quote 0
        • SGaist
          SGaist Lifetime Qt Champion last edited by

          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);@

          Interested in AI ? www.idiap.ch
          Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

          1 Reply Last reply Reply Quote 0
          • First post
            Last post