Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt Extensions
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. Qt Development
  3. General and Desktop
  4. QString to char* conversion
Forum Updated to NodeBB v4.3 + New Features

QString to char* conversion

Scheduled Pinned Locked Moved Solved General and Desktop
27 Posts 9 Posters 7.5k Views 4 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.
  • D Damian7546

    ok, but still doesn't works

    void C56SdkApp::PrintTest(QString text)
    {
    char* ch = text.toStdString().c_str();
    }
    

    Error:

    c56sdkapp.cpp:36:11: Cannot initialize a variable of type 'char *' with an rvalue of type 'const char *'
    

    so what can I do ?

    JohanSoloJ Offline
    JohanSoloJ Offline
    JohanSolo
    wrote on last edited by JohanSolo
    #4

    @Damian7546 said in QString to char* conversion:

    ok, but still doesn't works

    Error:
    c56sdkapp.cpp:36:11: Cannot initialize a variable of type 'char *' with an rvalue of type 'const char *'
    

    so what can I do ?

    Use

    const char* ch = text.toStdString().c_str();
    

    `They did not know it was impossible, so they did it.'
    -- Mark Twain

    1 Reply Last reply
    0
    • Chris KawaC Offline
      Chris KawaC Offline
      Chris Kawa
      Lifetime Qt Champion
      wrote on last edited by
      #5

      const char* ch will compile, but you can't use that afterwards. toStdString creates a temporary, which is destroysed after ;, so your variable points to released memory.

      If you want to use it in some function that takes a const char* as parameter you can do it either like this:

      SomeFunction(text.toStdString().c_str());   //temporary is in scope still
      

      or like this:

      std::string  s = text.toStdString();
      SomeFunction(s.c_str()); 
      

      but you can't do this:

      const char* ch = text.toStdString().c_str();
      //ch is pointing to garbage at this point
      SomeFunction(ch);
      
      JonBJ D 2 Replies Last reply
      5
      • Chris KawaC Chris Kawa

        const char* ch will compile, but you can't use that afterwards. toStdString creates a temporary, which is destroysed after ;, so your variable points to released memory.

        If you want to use it in some function that takes a const char* as parameter you can do it either like this:

        SomeFunction(text.toStdString().c_str());   //temporary is in scope still
        

        or like this:

        std::string  s = text.toStdString();
        SomeFunction(s.c_str()); 
        

        but you can't do this:

        const char* ch = text.toStdString().c_str();
        //ch is pointing to garbage at this point
        SomeFunction(ch);
        
        JonBJ Online
        JonBJ Online
        JonB
        wrote on last edited by
        #6

        @Chris-Kawa
        Why is the OP using toStdString.c_str() at all? What about, say, toUtf8().constData() or toLocal8Bit().constData(), are these any better/simpler/quicker?

        Chris KawaC 1 Reply Last reply
        1
        • JonBJ JonB

          @Chris-Kawa
          Why is the OP using toStdString.c_str() at all? What about, say, toUtf8().constData() or toLocal8Bit().constData(), are these any better/simpler/quicker?

          Chris KawaC Offline
          Chris KawaC Offline
          Chris Kawa
          Lifetime Qt Champion
          wrote on last edited by
          #7

          @JonB I don't know if they're better/simpler/quicker. I haven't measured. But one benefit would certainly be that they don't use std library to achieve the same result. Why use two libraries when you can do the same with one.

          JonBJ 1 Reply Last reply
          0
          • Chris KawaC Chris Kawa

            @JonB I don't know if they're better/simpler/quicker. I haven't measured. But one benefit would certainly be that they don't use std library to achieve the same result. Why use two libraries when you can do the same with one.

            JonBJ Online
            JonBJ Online
            JonB
            wrote on last edited by JonB
            #8

            @Chris-Kawa
            I'm relying on you to tell me/him! I have given up on trying to understand character encodings, it's too difficult, tg I'm English! But I think I read that toUtf8() would be for Linux while toLocal8Bit() (or toLatin()??) is for Windows, does that mean it's not platform independent while toStdString() is cross-platform?? Sigh....

            1 Reply Last reply
            0
            • E Offline
              E Offline
              Emre MUTLU
              wrote on last edited by Emre MUTLU
              #9

              you can try this:

              QString str="Something";
              qDebug()<<str.toLocal8Bit().constData();
              

              or

              QString str="Something";
              const char *ch=str.toLocal8Bit().constData();
              qDebug()<<ch;
              
              JonBJ 1 Reply Last reply
              1
              • E Emre MUTLU

                you can try this:

                QString str="Something";
                qDebug()<<str.toLocal8Bit().constData();
                

                or

                QString str="Something";
                const char *ch=str.toLocal8Bit().constData();
                qDebug()<<ch;
                
                JonBJ Online
                JonBJ Online
                JonB
                wrote on last edited by
                #10

                @Emre-MUTLU
                Yep, I agree, toLocal8Bit() seems to be the way to go. Maybe that's all std::string does anyway?

                M 1 Reply Last reply
                0
                • E Offline
                  E Offline
                  Emre MUTLU
                  wrote on last edited by
                  #11

                  i guess so yes

                  Chris KawaC 1 Reply Last reply
                  0
                  • E Emre MUTLU

                    i guess so yes

                    Chris KawaC Offline
                    Chris KawaC Offline
                    Chris Kawa
                    Lifetime Qt Champion
                    wrote on last edited by Chris Kawa
                    #12

                    @Emre-MUTLU As I said above you can't do this:

                    QString str="Something";
                    const char *ch=str.toLocal8Bit().constData();
                    qDebug()<<ch;
                    

                    toLocal8Bit returns a temporary object.

                    As to encodings - std::string does not dictate encoding. It's just a bag of bytes. toStdString and toUtf8 are the same i.e. return an UTF-8 string, just different containers. The first one is std::string and the other QByteArray.

                    toLocal8bit uses system locale, meaning the result will be different on different machines. Could be utf-8 on Linux, ISO 8859-1 or Windows-1252 in some European countries, some crazy stuff in asian languages or whatever the local encoding is on your machine. Note that QString is UTF-16 while local encoding can be fixed size 8bit, so using toLocal8Bit can be a lossy conversion. The docs say if any character can't be converted the result is undefined.

                    Which to use depends not on the functions themselves but on what you plan to do with the result. If you want to pass it to a function that accepts UTF-8 then use toUtf8(). If it's a system call that uses local codepage then toLocal8Bit. If it's a wide character WinAPI then toWCharArray etc.

                    Chris KawaC JonBJ 2 Replies Last reply
                    4
                    • Chris KawaC Chris Kawa

                      @Emre-MUTLU As I said above you can't do this:

                      QString str="Something";
                      const char *ch=str.toLocal8Bit().constData();
                      qDebug()<<ch;
                      

                      toLocal8Bit returns a temporary object.

                      As to encodings - std::string does not dictate encoding. It's just a bag of bytes. toStdString and toUtf8 are the same i.e. return an UTF-8 string, just different containers. The first one is std::string and the other QByteArray.

                      toLocal8bit uses system locale, meaning the result will be different on different machines. Could be utf-8 on Linux, ISO 8859-1 or Windows-1252 in some European countries, some crazy stuff in asian languages or whatever the local encoding is on your machine. Note that QString is UTF-16 while local encoding can be fixed size 8bit, so using toLocal8Bit can be a lossy conversion. The docs say if any character can't be converted the result is undefined.

                      Which to use depends not on the functions themselves but on what you plan to do with the result. If you want to pass it to a function that accepts UTF-8 then use toUtf8(). If it's a system call that uses local codepage then toLocal8Bit. If it's a wide character WinAPI then toWCharArray etc.

                      Chris KawaC Offline
                      Chris KawaC Offline
                      Chris Kawa
                      Lifetime Qt Champion
                      wrote on last edited by
                      #13

                      It's also worth mentioning that std::string was invented when UTF was not a common thing, so basically it sucks for anything that's multibyte. It can hold it fine, but methods like size() return the number of bytes, not characters. To get a length (in characters) of a multibyte string contained in std::string you have to use external function that understands multibyte. As such std::string is best suited for 8bit encodings, but technically is not limited to them.

                      1 Reply Last reply
                      2
                      • JonBJ JonB

                        @Emre-MUTLU
                        Yep, I agree, toLocal8Bit() seems to be the way to go. Maybe that's all std::string does anyway?

                        M Offline
                        M Offline
                        mpergand
                        wrote on last edited by
                        #14

                        @JonB said in QString to char* conversion:

                        @Emre-MUTLU
                        Yep, I agree, toLocal8Bit() seems to be the way to go. Maybe that's all std::string does anyway?

                        std::string is encoding agnostic, so the encoding is the one you choose to use.
                        ISO-8859 tried to be a "de facto standard" at least on windows and linux, but apple used MacRoman.
                        Before unicode/utf8 transcoding between OS was pure nightmare.

                        Christian EhrlicherC 1 Reply Last reply
                        0
                        • Chris KawaC Chris Kawa

                          @Emre-MUTLU As I said above you can't do this:

                          QString str="Something";
                          const char *ch=str.toLocal8Bit().constData();
                          qDebug()<<ch;
                          

                          toLocal8Bit returns a temporary object.

                          As to encodings - std::string does not dictate encoding. It's just a bag of bytes. toStdString and toUtf8 are the same i.e. return an UTF-8 string, just different containers. The first one is std::string and the other QByteArray.

                          toLocal8bit uses system locale, meaning the result will be different on different machines. Could be utf-8 on Linux, ISO 8859-1 or Windows-1252 in some European countries, some crazy stuff in asian languages or whatever the local encoding is on your machine. Note that QString is UTF-16 while local encoding can be fixed size 8bit, so using toLocal8Bit can be a lossy conversion. The docs say if any character can't be converted the result is undefined.

                          Which to use depends not on the functions themselves but on what you plan to do with the result. If you want to pass it to a function that accepts UTF-8 then use toUtf8(). If it's a system call that uses local codepage then toLocal8Bit. If it's a wide character WinAPI then toWCharArray etc.

                          JonBJ Online
                          JonBJ Online
                          JonB
                          wrote on last edited by
                          #15

                          @Chris-Kawa said in QString to char* conversion:

                          toLocal8Bit returns a temporary object.

                          I'm beginning to sense that all (not just some of) the QString::to...() methods return a temporary object. I wish the docs said so!!!!

                          Chris KawaC Christian EhrlicherC 2 Replies Last reply
                          0
                          • JonBJ JonB

                            @Chris-Kawa said in QString to char* conversion:

                            toLocal8Bit returns a temporary object.

                            I'm beginning to sense that all (not just some of) the QString::to...() methods return a temporary object. I wish the docs said so!!!!

                            Chris KawaC Offline
                            Chris KawaC Offline
                            Chris Kawa
                            Lifetime Qt Champion
                            wrote on last edited by Chris Kawa
                            #16

                            @JonB Well most functions return temporaries e.g. std::string foo() { return "something"; } is a temporary. It just depends on how you use them. The docs would have to say that on everything that doesn't return a pointer or a reference.

                            foo();  // returns an r-value (temporary) that is never used, so destroyed immediately
                            
                            SomeFunction(foo()); //returns an r-value and passes it into the function. Lives in the scope of the function call.
                            
                            std::string s = foo(); //returns an r-value and assigns it to a new variable. 
                            

                            in this last case RVO also kicks in.

                            1 Reply Last reply
                            1
                            • JonBJ JonB

                              @Chris-Kawa said in QString to char* conversion:

                              toLocal8Bit returns a temporary object.

                              I'm beginning to sense that all (not just some of) the QString::to...() methods return a temporary object. I wish the docs said so!!!!

                              Christian EhrlicherC Online
                              Christian EhrlicherC Online
                              Christian Ehrlicher
                              Lifetime Qt Champion
                              wrote on last edited by
                              #17

                              @JonB said in QString to char* conversion:

                              I wish the docs said so!!!!

                              As soon as an object is returned from any function (even a plain C function) it's a temporary until you assign it to a local variable.

                              Qt Online Installer direct download: https://download.qt.io/official_releases/online_installers/
                              Visit the Qt Academy at https://academy.qt.io/catalog

                              J.HilkJ 1 Reply Last reply
                              0
                              • M mpergand

                                @JonB said in QString to char* conversion:

                                @Emre-MUTLU
                                Yep, I agree, toLocal8Bit() seems to be the way to go. Maybe that's all std::string does anyway?

                                std::string is encoding agnostic, so the encoding is the one you choose to use.
                                ISO-8859 tried to be a "de facto standard" at least on windows and linux, but apple used MacRoman.
                                Before unicode/utf8 transcoding between OS was pure nightmare.

                                Christian EhrlicherC Online
                                Christian EhrlicherC Online
                                Christian Ehrlicher
                                Lifetime Qt Champion
                                wrote on last edited by
                                #18

                                @mpergand said in QString to char* conversion:

                                std::string is encoding agnostic, so the encoding is the one you choose to use.

                                And Qt defines that every std::string created from QString is UTF-8 encoded:

                                inline std::string QString::toStdString() const
                                { return toUtf8().toStdString(); }
                                

                                Even QString::toLocal8Bit() on Linux assumes the locale is UTF-8 - encoded without looking at the real locale, on Window the locale is respected.

                                Qt Online Installer direct download: https://download.qt.io/official_releases/online_installers/
                                Visit the Qt Academy at https://academy.qt.io/catalog

                                1 Reply Last reply
                                0
                                • Chris KawaC Chris Kawa

                                  const char* ch will compile, but you can't use that afterwards. toStdString creates a temporary, which is destroysed after ;, so your variable points to released memory.

                                  If you want to use it in some function that takes a const char* as parameter you can do it either like this:

                                  SomeFunction(text.toStdString().c_str());   //temporary is in scope still
                                  

                                  or like this:

                                  std::string  s = text.toStdString();
                                  SomeFunction(s.c_str()); 
                                  

                                  but you can't do this:

                                  const char* ch = text.toStdString().c_str();
                                  //ch is pointing to garbage at this point
                                  SomeFunction(ch);
                                  
                                  D Offline
                                  D Offline
                                  Damian7546
                                  wrote on last edited by Damian7546
                                  #19

                                  @Chris-Kawa
                                  I would like to pass QString to pszTxt parameter in this function:
                                  fun1(HANDLE hDocument, PSTR pszTxt)

                                  Below doesn't works:

                                  void C56SdkApp::PrintTest(QString text)
                                  {
                                      char* ch = text.toUtf8().toStdString();
                                      fun1(hDocument,  ch );
                                  }
                                  
                                  1 Reply Last reply
                                  0
                                  • Chris KawaC Offline
                                    Chris KawaC Offline
                                    Chris Kawa
                                    Lifetime Qt Champion
                                    wrote on last edited by
                                    #20

                                    @Damian7546 Well it doesn't work because you're assigning std::string to char* variable. It doesn't make any sense.

                                    You have to check what encoding the function fun1 expects in its pszTxt parameter.
                                    If its local codepage then

                                    fun1(hDocument,  text.toLocal8Bit().constData());
                                    

                                    If it's UTF-8 then

                                    fun1(hDocument,  text.toUtf8().constData());
                                    
                                    D 1 Reply Last reply
                                    0
                                    • Christian EhrlicherC Christian Ehrlicher

                                      @JonB said in QString to char* conversion:

                                      I wish the docs said so!!!!

                                      As soon as an object is returned from any function (even a plain C function) it's a temporary until you assign it to a local variable.

                                      J.HilkJ Offline
                                      J.HilkJ Offline
                                      J.Hilk
                                      Moderators
                                      wrote on last edited by
                                      #21

                                      @Christian-Ehrlicher said in QString to char* conversion:

                                      As soon as an object is returned from any function (even a plain C function) it's a temporary until you assign it to a local variable.

                                      any ? what if I returned a static object ?


                                      Be aware of the Qt Code of Conduct, when posting : https://forum.qt.io/topic/113070/qt-code-of-conduct


                                      Q: What's that?
                                      A: It's blue light.
                                      Q: What does it do?
                                      A: It turns blue.

                                      Chris KawaC 1 Reply Last reply
                                      0
                                      • J.HilkJ J.Hilk

                                        @Christian-Ehrlicher said in QString to char* conversion:

                                        As soon as an object is returned from any function (even a plain C function) it's a temporary until you assign it to a local variable.

                                        any ? what if I returned a static object ?

                                        Chris KawaC Offline
                                        Chris KawaC Offline
                                        Chris Kawa
                                        Lifetime Qt Champion
                                        wrote on last edited by Chris Kawa
                                        #22

                                        @J-Hilk said in QString to char* conversion:

                                        any ? what if I returned a static object ?

                                        If you return it by value it's still a temporary (copy), unless you return a reference. But even if you do it's technically still a temporary. It's just that the reference is a temporary, not the object it references. To simplify - anything that doesn't have a name is a temporary.

                                        1 Reply Last reply
                                        0
                                        • Chris KawaC Chris Kawa

                                          @Damian7546 Well it doesn't work because you're assigning std::string to char* variable. It doesn't make any sense.

                                          You have to check what encoding the function fun1 expects in its pszTxt parameter.
                                          If its local codepage then

                                          fun1(hDocument,  text.toLocal8Bit().constData());
                                          

                                          If it's UTF-8 then

                                          fun1(hDocument,  text.toUtf8().constData());
                                          
                                          D Offline
                                          D Offline
                                          Damian7546
                                          wrote on last edited by
                                          #23

                                          @Chris-Kawa said in QString to char* conversion:

                                          @Damian7546 Well it doesn't work because you're assigning std::string to char* variable. It doesn't make any sense.
                                          You have to check what encoding the function fun1 expects in its pszTxt parameter.
                                          If its local codepage then
                                          fun1(hDocument, text.toLocal8Bit().constData());

                                          If it's UTF-8 then
                                          fun1(hDocument, text.toUtf8().constData());

                                          But in this way doesn't works. -> No matching fuction for call to fun1

                                          Christian EhrlicherC Chris KawaC 2 Replies 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