可能重复:
QString转char*的转换方法
我有一个函数(STL中的fopen)需要使用计算机上的路径作为char*参数,但是我必须在这个位置使用QString,所以它不能工作。
如何将QString转换为char *以解决此问题?
可能重复:
QString转char*的转换方法
我有一个函数(STL中的fopen)需要使用计算机上的路径作为char*参数,但是我必须在这个位置使用QString,所以它不能工作。
如何将QString转换为char *以解决此问题?
当然,我发现有另一种方法可以从之前的SO回答中得到信息: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#toLatin1 https://doc.qt.io/qt-5/qbytearray.html#data
See the following example for a demonstration:
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(); }
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();
will make the application crash as the QByteArray has not been stored and hence no longer exists
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)) ;
See the documentation:
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();
你可以使用QFile而不是std::fstream。
QFile file(qString);
或者将QString转换为char*,如下所示:
std::ifstream file(qString.toLatin1().data());
QString 是使用 UTF-16 编码的,因此在这里进行了转换为 Latin1(),但 QString 还有一些其他的转换方式,包括 toUtf8()(请检查您的文件系统,它可能使用 UTF-8)。
如@0A0D所述:不要将 char* 存储在变量中而不获取 QByteArray 的本地副本。
char const* fileName = qString.toLatin1().data();
std::ifstream file(fileName); // fileName not valid here.
const char *c_str2 = str2.toLatin1().data();
应该可以正常工作。不幸的是,分号后由 toLatin1() 创建的临时 QByteArray 已被销毁,因此c_str2
现在具有无效指针。相反,您可以在调用中使用它doStuff(str2.toLatin1().data());
因为 QByteArray 直到 ';' 才被销毁。因此:printf("str2: %s", str2.toLatin1().data());
应该没问题。 - Martin YorkQString
仅包含有效的Latin1字符时才有效。 - jrh