2016-12-26 69 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