Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt Extensions
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. Qt Development
  3. Language Bindings
  4. Differences between QString conversion using .toAscii(), .toAscii().data(), or to toLocal8Bit().data()?
Forum Updated to NodeBB v4.3 + New Features

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

Scheduled Pinned Locked Moved Language Bindings
3 Posts 3 Posters 5.2k Views 1 Watching
  • 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 Offline
    K Offline
    knowNothing
    wrote on last edited by
    #1

    Hello all,

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

    1 Reply Last reply
    0
    • J Offline
      J Offline
      JvdGlind
      wrote on last edited by
      #2

      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
      0
      • SGaistS Offline
        SGaistS Offline
        SGaist
        Lifetime Qt Champion
        wrote on last edited by
        #3

        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
        0

        • Login

        • Login or register to search.
        • First post
          Last post
        0
        • Categories
        • Recent
        • Tags
        • Popular
        • Users
        • Groups
        • Search
        • Get Qt Extensions
        • Unsolved