6

I have read a string in from an XML file with UTF8 encoding. I store this value in a QString object and concatenate it with some other information. I can see in the QtCreator debugger that the QString holds the desired value.

I need to pass this string to another library that takes a const char * argument. How do I obtain the const char * please? I've tried toLocal8bit(), toLatin1(), toUtf8() all with no luck. Seems like I am missing something...

Angie Quijano
  • 4,167
  • 3
  • 25
  • 30
narmaps
  • 373
  • 5
  • 16
  • http://stackoverflow.com/questions/4214369/how-to-convert-qstring-to-stdstring – Min Lin Sep 25 '13 at 04:06
  • @MinLin: that thread is about std string, *not* const char*. – László Papp Sep 25 '13 at 06:41
  • @LaszloPapp Well, in the answer the rvalue is const char*, just implicitly converted to the lvalue which is a std string – Min Lin Sep 25 '13 at 06:45
  • @MinLin: std::string and QString should not be mixed IMO as it is not necessary. Hence, that is a different use case, so a different question. It is better to go through qt types without mixing std in. See my answer below. – László Papp Sep 25 '13 at 06:47
  • @LaszloPapp Well, your answer is correct. What I mean is that in that post though it wants a std string, the right hand side is a const char*, and I think readers of that post should be able to figure out. – Min Lin Sep 25 '13 at 10:21
  • Possible duplicate of [QString to char\* conversion](https://stackoverflow.com/questions/2523765/qstring-to-char-conversion) – Ben Jones Jul 27 '18 at 20:46

1 Answers1

10

I need to pass this string to another library that takes a const char * argument. How do I obtain the const char * please? I've tried toLocal8bit(), toLatin1(), toUtf8() all with no luck. Seems like I am missing something...

Because if you try those, you only get a QByteArray back as opposed to a const char*. You could use the constData() method on the QByteArray you got that way, and then you will have the desired result.

Mixing std::string and QString is not necessary, hence it is better to go through the qt types (QString -> QByteArray -> const char*) without introducing std::string in here.

Where you use toLocal8bit(), toLatin1() or toUtf8() depends on your encoding, so that is a different question to the main one in here. They will all return a QByteArray to you.

Note: you should avoid using toAscii() though as that is deprecated in Qt 5 for good.

Mohammad Kanan
  • 4,452
  • 10
  • 23
  • 47
László Papp
  • 51,870
  • 39
  • 111
  • 135