I am trying to do something like this:
QString string;
// do things...
std::cout << string << std::endl;
but the code doesn't compile. How to output the content of qstring into the console (e.g. for debugging purposes or other reasons)? How to convert QString
to std::string
?
One of the things you should remember when converting
QString
tostd::string
is the fact thatQString
is UTF-16 encoded whilestd::string
... May have any encodings.So the best would be either:
The suggested (accepted) method may work if you specify codec.
See: http://doc.qt.io/qt-5/qstring.html#toLatin1
You can use:
Here's reference documentation for
QString
.If your ultimate aim is to get debugging messages to the console, you can use qDebug().
You can use like,
qDebug()<<string;
which will print the contents to the console.This way is better than converting it into
std::string
just for the sake of debugging messages.However, if you're using Qt:
Best thing to do would be to overload operator<< yourself, so that QString can be passed as a type to any library expecting an output-able type.
An alternative to the proposed:
could be:
See qPrintable documentation, a macro delivering a const char * from QtGlobal.
The simplest way would be
QString::toStdString()
.You can use this;
could even throw exception on VS2017 compiler in xstring
the right way ( secure - no exception) is how is explained above from Artyom
Try this: