2012-08-14 88 views
0

我試着寫在Linux中wstrings(俄文),在C++下面的代碼代碼:無法寫入帶俄語字符wstring的提交

ofstream outWFile; 
outWFile.open("input.tab"); 
outWFile<< WStringToString(w->get_form()); 
outWFile<<"\t"; 
outWFile<<WStringToString(w->get_tag()); 

std::string WStringToString(const std::wstring& s) 
{ 
    std::string temp(s.length(),' '); 
    std::copy(s.begin(), s.end(), temp.begin()); 
    return temp; 
} 

input.tab內容是無效的

我試圖做什麼建議在stackoverflow包括 Unable to write a std::wstring into wofstream 但我沒有幫助。 預先感謝您

+0

可能重複的[無法寫入一個std :: wstring的成wofstream](http://stackoverflow.com/questions/5104329/unable-to-write-a-stdwstring-into-wofstream) – Griwes 2012-08-14 20:35:48

+0

那些'ostream <<'應該是'outWFile'? – Etherealone 2012-08-14 20:38:41

+0

您的代碼根本不顯示寫入文件,只顯示標準輸出。 – bames53 2012-08-14 21:03:20

回答

0

您的轉換函數有問題:它將最終搞亂代碼點爲128/256或更大(取決於您的區域設置)的所有字符。

改爲使用wcstombs(確保使用UTF-8語言環境)。

+0

WStringToString肯定是錯誤的,但不清楚它是用來寫入文件的。另外,我不會建議依靠像wcstombs這樣的基於區域的轉換,因爲您提到的原因;你必須確保語言環境適合你的使用,如果它不是必須改變。這不可靠或用戶友好。只有當您確實想使用語言環境編碼時,才能使用基於語言環境的轉換,而不管它們是什麼(並且這是罕見的IME)。 – bames53 2012-08-14 20:44:13

+0

@ bames53:是的,語言環境可能會導致問題。我個人使用UTF-8語言環境假設(在適用的情況下)使用我的Linux編碼大部分,就像任何現代Linux系統一樣,但我想我可能已經提出了一些不那麼脆弱的東西,現在C++有內置的Unicode工具。 – 2012-08-14 20:50:36

+0

是的,我也只是假設UTF-8總是適用於所有內容,並忽略語言環境編碼。只有那些應得的人才會遇到問題。 – bames53 2012-08-14 20:53:10

0

我想你會更好地直接使用wstring內容。

outWfile.write(w->get_tag()->data(), w->get_tag()->size()*sizeof(wchar_t)); 
// I used data() assuming the string and wstring methods are the same? 
// Anyhow, get the pointer to wstring's data here.