How to convert QString to const char *
Hi,
Is there any way to convert a QString to a const char * ?
Thanks.
9 replies
You can do this:
char* myChar = myString.toStdString().c_str();
Take care of the lifetime of these variables!
if you have an in parameter, you can do such things, although I would not got the way with std::string:
- void foo(const char*);
- QSTring text;
- foo(text.toUtf8().constData());
aditionally, check:
- QByteArray toAscii () const
- QByteArray toLatin1 () const
- QByteArray toLocal8Bit () const
It’s up to you, which encoding you use.
But all these functions return temporary objects, and calling constData returns the buffer of the temp objects. In the next line of code (when foo() returns) the temp object is destroyed and the buffer gets invalid!
Why should the be no way? I showed you some…
it is, but which format do you need?
- utf8?
- 7-bit ASCII?
- 8-bit ASCI with with regional code?
- MBCS?
all are conat char* formats.
QString is unicode.
in general, it is possible:
- QString text;
- std::string s = text.toLatin1().constData;
- foo(s.c_str());
If you really need a const char* I would convert it to and std::string (but reagrd the conversion!) and use the std::string. Who shall otherwise handle the memory? who shall allocate it? who shall free it?
you can also do the following:
- QString text;
- chat* p = new char[text.length() + 1);
- strcpy(p, text.toLatin1().constData());
Take care that text.length() might not valid if you then convert to utf8!
You must log in to post a reply. Not a member yet? Register here!





