我正在尝试这样做:

QString string;
// do things...
std::cout << string << std::endl;

但是代码不能编译。 如何将qstring的内容输出到控制台(例如用于调试目的或其他原因)?如何将QString转换为std::string?


当前回答

当将QString转换为std::string时,你应该记住的一件事是,QString是UTF-16编码的,而std::string…可能有任何编码。

所以最好的选择是:

QString qs;

// Either this if you use UTF-8 anywhere
std::string utf8_text = qs.toUtf8().constData();

// or this if you're on Windows :-)
std::string current_locale_text = qs.toLocal8Bit().constData();

如果指定了编解码器,建议的(可接受的)方法可能有效。

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

其他回答

当将QString转换为std::string时,你应该记住的一件事是,QString是UTF-16编码的,而std::string…可能有任何编码。

所以最好的选择是:

QString qs;

// Either this if you use UTF-8 anywhere
std::string utf8_text = qs.toUtf8().constData();

// or this if you're on Windows :-)
std::string current_locale_text = qs.toLocal8Bit().constData();

如果指定了编解码器,建议的(可接受的)方法可能有效。

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

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

但是,如果你使用的是Qt:

QTextStream out(stdout);
out << qstr;

你可以用这个;

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

提议的替代方案:

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

可能是:

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

参见qPrintable文档,一个从QtGlobal传递const char *的宏。

你可以使用:

QString qs;
// do things
std::cout << qs.toStdString() << std::endl;

它内部使用QString::toUtf8()函数来创建std::string,所以它也是Unicode安全的。下面是QString的参考文档。