我正在尝试这样做:
QString string;
// do things...
std::cout << string << std::endl;
但是代码不能编译。 如何将qstring的内容输出到控制台(例如用于调试目的或其他原因)?如何将QString转换为std::string?
我正在尝试这样做:
QString string;
// do things...
std::cout << string << std::endl;
但是代码不能编译。 如何将qstring的内容输出到控制台(例如用于调试目的或其他原因)?如何将QString转换为std::string?
当前回答
试试这个:
#include <QDebug>
QString string;
// do things...
qDebug() << "right" << string << std::endl;
其他回答
QString qstr;
std::string str = qstr.toStdString();
但是,如果你使用的是Qt:
QTextStream out(stdout);
out << qstr;
当将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
试试这个:
#include <QDebug>
QString string;
// do things...
qDebug() << "right" << string << std::endl;
QString data;
data.toStdString().c_str();
甚至可以抛出异常VS2017编译器在xstring
~basic_string() _NOEXCEPT
{ // destroy the string
_Tidy_deallocate();
}
正确的方法(安全-没有例外)是Artyom上面解释的
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();
最简单的方法是QString::toStdString()。