2011-02-24 52 views
3

我在Linux系統上使用Qt/C++。我需要將QLineEdit的文本轉換爲std::wstring並將其寫入std::wofstream。它對ascii字符串正常工作,但是當我輸入任何其他字符(阿拉伯語或烏茲別克語)時,文件中沒有寫入任何內容。 (文件的大小是0字節)。無法在wofstream中寫入std :: wstring

這是我的代碼:

wofstream customersFile; 
customersFile.open("./customers.txt"); 
std::wstring ws = lne_address_customer->text().toStdWString(); 
customersFile << ws << ws.length() << std::endl; 

輸出爲行編輯進入John SmithJohn Smith10。但對於unicode字符串,什麼都沒有。

首先,我認爲這是QString::toStdWString()的問題,但customersFile << ws.length();寫入所有字符串的正確長度。所以我想我在寫文件wstring時做錯了什麼。 [?]

編輯:

我在eclipse中再次寫它。並用g ++ 4.5編譯它。結果是一樣的:

#include <iostream> 
#include <string> 
#include <fstream> 

using namespace std; 

int main() 
{ 
    cout << "" << endl; // prints 
    wstring ws = L"سلام"; // this is an Arabic "Hello" 
    wofstream wf("new.txt"); 
    if (!wf.bad()) 
     wf << ws; 
    else 
     cerr << "some problem"; 
    return 0; 
} 
+0

@Sorush Rabiee,請您在最後一行的末尾添加的std :: ENDL: 'customersFile << ws << ws.length()<< std :: endl'只是爲了確保刷新已完成 – Dewfy 2011-02-24 12:00:34

+0

@Dewfy:好的,但沒有任何更改... – 2011-02-24 12:04:11

+1

customersFile上的狀態標誌是什麼? customersFile充滿了支持unicode的語言環境嗎? – AProgrammer 2011-02-24 12:22:53

回答

13

添加

#include <locale> 

,並在主要的開始,

std::locale::global(std::locale("")); 
+1

as described [here](http://stackoverflow.com/questions/1509277/why-does-wide-file-stream-in-c-narrow-written-data-by-default?rq=1)這是'環境確定區域設置'。一個更通用的解決方案[這裏](http://stackoverflow.com/questions/9859020/windows-unicode-c-stream-output-failure/9869272#9869272) – mzzzzb 2014-07-31 16:52:43