問題描述
可能的重復(fù):
QString 到 char 的轉(zhuǎn)換
我有一個函數(shù)(STL 中的 fopen),它提供一個 char* 參數(shù)作為我計算機中的路徑,但我必須在那個地方使用 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轉(zhuǎn)為char*來解決這個問題?
How can I convert QString to char* to solve this problem?
推薦答案
參見 這里是 How我可以將 QString 轉(zhuǎn)換為 char*,反之亦然嗎?
為了將 QString 轉(zhuǎn)換為char*,那么你首先需要得到一個字符串的 latin1 表示形式調(diào)用 toLatin1() 它將返回一個 QByteArray.然后調(diào)用data()在 QByteArray 上獲取指向的指針存儲在字節(jié)數(shù)組中的數(shù)據(jù).看文檔:
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();
}
注意,需要存儲在調(diào)用 data() 之前的 bytearray它,像下面這樣的調(diào)用
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();
會使應(yīng)用程序崩潰,因為QByteArray 沒有被存儲并且因此不再存在
will make the application crash as the QByteArray has not been stored and hence no longer exists
要將 char* 轉(zhuǎn)換為 QString可以使用 QString 構(gòu)造函數(shù)接受 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
當(dāng)然,我發(fā)現(xiàn)從這個以前的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();
這篇關(guān)于將 QString 轉(zhuǎn)換為 char*的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!