2011-03-31 89 views

回答

44

here at How can I convert a QString to char* and vice versa?

爲了爲QString轉換爲 的char *,那麼你首先需要通過 得到字符串的 的latin1表示它調用toLatin1(),這將 返回QByteArray中。然後調用QByteArray上的數據() 來獲取指向 存儲在字節數組中的數據。見 文檔:

http://qt.nokia.com/doc/qstring.html#toLatin1 http://qt.nokia.com/doc/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(); 
} 

注意,有必要存儲 的bytearray你 呼叫數據()之前它,像下面的電話

const char *c_str2 = str2.toLatin1().data(); 

將使應用程序崩潰的 的QByteArray沒有被儲存和 因此不再存在

爲char *轉換爲你 可以使用QString的構造函數 需要QLatin1String,如QString的:

QString string = QString(QLatin1String(c_str2)) ; 

參見文檔:

http://qt.nokia.com/doc/qlatin1string.html

當然,我發現有從這個previous SO answer另一種方式:

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(); 
+8

我認爲措辭需要改變。聲明'const char * c_str2 = str2.toLatin1()。data();'應該可以正常工作。不幸的是,';'由toLatin1()創建的臨時QByteArray已被銷燬,因此'c_str2'現在有一個無效指針。相反,你可以在調用'doStuff(str2.toLatin1()。data());'中使用它,因爲QByteArray不會被銷燬,直到';'因此:'printf(「str2:%s」,str2.toLatin1()。data());'應該可以。 – 2011-03-31 20:46:21

+0

@Martin:我只是引用Qt。 – 2011-03-31 20:49:01

+1

這個。今天我花了一半時間調試QByteArray被破壞引起的問題。必須存儲字節數組真的很痛苦,但似乎是必要的。 – misha 2011-11-14 11:24:08

1

你可以使用QFile而不是的std :: fstream的。

QFile   file(qString); 

替代地,QString的轉換成一個char *如下:

std::ifstream file(qString.toLatin1().data()); 

QString是UTF-16,從而它被轉換toLatin1()在這裏,但QString的有幾個不同的轉換,包括toUtf8的()(檢查你的文件系統可能使用UTF-8)。

正如上面的@ 0A0D所指出的那樣:不要將char *存儲在變量中,而不會獲取QByteArray的本地副本。

char const*  fileName = qString.toLatin1().data(); 
std::ifstream file(fileName); // fileName not valid here. 

這是因爲toLatin1()返回一個QByteArray對象。由於它實際上並未綁定到變量,因此它是在表達式末尾銷燬的臨時變量。因此,這裏對data()的調用返回一個指向內部結構的指針,該內部結構在';'之後不再存在。