带有口音的宽字符串未输出

wide strings with accents are not outputted

本文关键字:字符串 未输 输出      更新时间:2023-10-16

当我插入带有口音的字符串时,它不会显示在" 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)TOCsalut自动

其余的重音单词未写(我猜流错误)。

该程序是用G 编译的,源文件编码为UTF-8。

我注意到控制台输出相同的行为。

我该如何解决?

因为您没有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编码文件。

因此,我建议使用UTF8:

  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;