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...
You absolutely can assign const char* to std::string , it will get copied though. The other way around requires a call to std::string::c_str() .
You can use: QString qs; // do things std::cout << qs. toStdString() << std::endl; It internally uses QString::toUtf8() function to create std::string, so it's Unicode safe as well.
7.8 Member Function Return Types const char* function (...) returns a pointer to data that cannot change. The caller can see the data but the compiler will reject any code that may change the data. The caller must assign the result to a const char* variable or pass as a const char* argument.
Generally speaking: If you want to initialize a QString from a char*, use QStringLiteral . If you want to pass it to a method, check if that method has an overload for QLatin1String - if yes you can use that one, otherwise fall back to QStringLiteral .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With