2016-12-26 67 views
0

當我插入帶有重音的字符串,它不將文件「FAKE.txt」(UTF-16編碼)帶有重音寬字符串不輸出

std::wifstream ifFake("FAKE.txt", std::ios::binary); 
     ifFake.imbue(std::locale(ifFake.getloc(), 
     new std::codecvt_utf16<wchar_t, 0x10ffff, std::consume_header>)); 
     if (!ifFake) 
     { 
     std::wofstream ofFake("FAKE.txt", std::ios::binary); 
     ofFake << L"toc" << std::endl; 
     ofFake << L"salut" << std::endl; 
     ofFake << L"autre" << std::endl; 
     ofFake << L"êtres" << std::endl; 
     ofFake << L"âpres" << std::endl; 
     ofFake << L"bêtes" << std::endl; 
     } 

結果中顯示出來(FAKE.txt ) toc salut autre

重音字的其餘部分沒有被寫入(流錯誤我猜)。

該程序是用g ++編譯的,源文件編碼是UTF-8。

我注意到與控制檯輸出相同的行爲。

我該如何解決這個問題?

回答

1

因爲您沒有imbue區域設置爲ofFake

下面的代碼應該很好地工作:

std::wofstream ofFake("FAKE.txt", std::ios::binary); 
    ofFake.imbue(std::locale(ofFake.getloc(), 
       new std::codecvt_utf16<wchar_t, 0x10ffff, std::generate_header>)); 
    ofFake << std::wstring(L"toc") << std::endl; 
    ofFake << L"salut" << std::endl; 
    ofFake << L"autre" << std::endl; 
    ofFake << L"êtres" << std::endl; 
    ofFake << L"âpres" << std::endl; 
    ofFake << L"bêtes" << std::endl; 

雖然只有MSVC++二進制將UTF-16編碼文件。 g ++二進制看起來像是用一些無用的BOM製作一個UTF8編碼的文件。

因此,我建議使用UTF-8改爲:

std::wofstream ofFake("FAKE.txt", std::ios::binary); 
    ofFake.imbue(std::locale(ofFake.getloc(), new std::codecvt_utf8<wchar_t>)); 
    ofFake << L"toc" << std::endl; 
    ofFake << L"salut" << std::endl; 
    ofFake << L"autre" << std::endl; 
    ofFake << L"êtres" << std::endl; 
    ofFake << L"âpres" << std::endl; 
    ofFake << L"bêtes" << std::endl; 
+0

謝謝!你對g ++是正確的。我會嘗試你的第二個解決方案。 – Aminos