Converting QString to char*(将 QString 转换为 char*)
问题描述
可能的重复:
QString 到 char 的转换
我有一个函数(STL 中的 fopen),它提供一个 char* 参数作为我计算机中的路径,但我必须在那个地方使用 QString,所以它不起作用.
I have a function (fopen in STL) that gives a char* argument as a path in my computer, but I must use QString in that place so it doesn't work.
如何将QString转为char*来解决这个问题?
How can I convert QString to char* to solve this problem?
推荐答案
参见 这里是 How我可以将 QString 转换为 char*,反之亦然吗?
为了将 QString 转换为char*,那么你首先需要得到一个字符串的 latin1 表示形式调用 toLatin1() 它将返回一个 QByteArray.然后调用data()在 QByteArray 上获取指向的指针存储在字节数组中的数据.看文档:
In order to convert a QString to a char*, then you first need to get a latin1 representation of the string by calling toLatin1() on it which will return a QByteArray. Then call data() on the QByteArray to get a pointer to the data stored in the byte array. See the documentation:
https://doc.qt.io/qt-5/qstring.html#toLatin1https://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它,像下面这样的调用
Note that it is necessary to store the bytearray before you call data() on it, a call like the following
const char *c_str2 = str2.toLatin1().data();
会使应用程序崩溃,因为QByteArray 没有被存储并且因此不再存在
will make the application crash as the QByteArray has not been stored and hence no longer exists
要将 char* 转换为 QString可以使用 QString 构造函数接受 QLatin1String,例如:
To convert a char* to a QString you can use the QString constructor that takes a QLatin1String, e.g:
QString string = QString(QLatin1String(c_str2)) ;
查看文档:
https://doc.qt.io/qt-5/qlatin1string.html
当然,我发现从这个以前的SO还有另一种方式答案:
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();
这篇关于将 QString 转换为 char*的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:将 QString 转换为 char*


基础教程推荐
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 常量变量在标题中不起作用 2021-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 这个宏可以转换成函数吗? 2022-01-01