可能的重复:
QString 到 char 的转换 https://stackoverflow.com/questions/2523765/qstring-to-char-conversion
我有一个函数(STL 中的 fopen)提供 char* 参数作为我计算机中的路径,但我必须在该位置使用 QString,因此它不起作用。
如何将 QString 转换为 char* 来解决这个问题?
See 在如何将 QString 转换为 char* ,反之亦然? http://developer.qt.nokia.com/faq/answer/how_can_i_convert_a_qstring_to_char_and_vice_versa
为了将 QString 转换为
char*,那么你首先需要得到一个
字符串的 latin1 表示形式
调用 toLatin1() 将会
返回一个 QByteArray。然后调用data()
在 QByteArray 上获取指向的指针
存储在字节数组中的数据。看
文档:
https://doc.qt.io/qt-5/qstring.html#toLatin1 https://doc.qt.io/qt-5/qstring.html#toLatin1
https://doc.qt.io/qt-5/qbytearray.html#data https://doc.qt.io/qt-5/qbytearray.html#data
请参阅以下示例
示范:
int main(int argc, char **argv)
{
QApplication app(argc, argv);
QString str1 = "Test";
QByteArray ba = str1.toLatin1();
const char *c_str2 = ba.data();
printf("str2: %s", c_str2);
return app.exec();
}
请注意,需要存储
在调用 data() 之前的 bytearray
它,像下面这样的调用
const char *c_str2 = str2.toLatin1().data();
将使应用程序崩溃
QByteArray 尚未存储并且
因此不再存在
要将 char* 转换为 QString,您
可以使用 QString 构造函数
采用 QLatin1String,例如:
QString string = QString(QLatin1String(c_str2)) ;
请参阅文档:
https://doc.qt.io/qt-5/qlatin1string.html https://doc.qt.io/qt-5/qlatin1string.html
当然,我发现还有另一种方法以前的答案 https://stackoverflow.com/questions/4214369/how-to-convert-qstring-to-stdstring/4644922#4644922:
QString qs;
// Either this if you use UTF-8 anywhere
std::string utf8_text = qs.toUtf8().constData();
// or this if you on Windows :-)
std::string current_locale_text = qs.toLocal8Bit().constData();
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)