How do I convert QString to std:: string?

I tried to do this:

QString string;
// делаю так ...
std::cout << string << std::endl;

But the problem is, the code is not going to be collected.How do I output the contents of a qstring to the console (for example, for debugging purposes or for other reasons)? How do I convert QString to std:: string?

This question, translation of the question: https://stackoverflow.com/questions/4214369/how-to-convert-qstring-to-stdstring

Author: Anton Shchyrov, 2018-06-01

1 answers

One thing to keep in mind when converting QString to std:: string is that QString is encoded in UTF-16, and std :: string ... It can have any encoding.

Here are the best ways:

QString qs;

// можно использовать такой способ если пользуетесь UTF-8 в любом месте
std::string utf8_text = qs.toUtf8().constData();

// или таким способом если вы в Windows :-)
std::string current_locale_text = qs.toLocal8Bit().constData();

The suggested (accepted) method may work if you specify the codec.

See: http://doc.qt.io/qt-5/qstring.html#toLatin1


You can use:

QString qs;
// делай так
std::cout << qs.toStdString() << std::endl;

Here is the reference documentation for QString.


If your ultimate goal is to get debug messages on the console, you can use qDebug ().

You can use,

#include <QDebug> // в заголовке файла (.cpp либо .h)

qDebug() << "строка"; // выводим надпись на консоль
QString str = "строка";
qDebug() << str; // выводим надпись на консоль

This method is better than converting it to std :: string , but only for debugging messages(or using it as reference points in the created application(so to speak, such a "half-blogger") ).

qDebug() for debugging messages much better, because it supports more types Qt


QString qstr;
std::string str = qstr.toStdString();

However, if you use Qt:

QTextStream out(stdout);
out << qstr;

The best way is to overload the

std::ostream& operator<<(std::ostream& str, const QString& string) {
    return str << string.toStdString();
}

Alternative to the proposed:

QString qs;
std :: string current_locale_text = qs.toLocal8Bit (). constData ();

Can still be:

QString qs;
std :: string current_locale_text = qPrintable (qs);

See the documentation for qPrintable, a macro that provides const char * from QtGlobal.


The simplest way is QString::toStdString().


You can use this :

QString data;
data.toStdString().c_str();

Translator's notes : I use it myself for output to the console qDebug().

 1
Author: timob256, 2018-06-01 10:14:04