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();
~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();
10 回答
将
QString
转换为std::string
时应该记住的一件事是QString
是UTF-16编码而std::string
...可能有任何编码 .所以最好的是:
如果指定编解码器,建议的(接受的)方法可能有效 .
见:http://doc.qt.io/qt-5/qstring.html#toLatin1
您可以使用:
Here's
QString
的参考文献 .如果您的最终目标是将调试消息发送到控制台,则可以使用qDebug() .
你可以使用喜欢,
qDebug()<<string;
将打印内容到控制台 .这种方式比仅仅为了调试消息而将其转换为
std::string
更好 .但是,如果您使用的是Qt:
最好的办法是重载operator << self,这样QString就可以作为一个类型传递给任何期望输出类型的库 .
建议的替代方案:
可能:
请参阅qPrintable documentation,一个从QtGlobal传递const char *的宏 .
最简单的方法是
QString::toStdString()
.你可以用这个;
甚至可以在xstring中的VS2017编译器上抛出异常
正确的方法(安全 - 也不例外)是如何从Artyom解释的
试试这个: