5

As we know when writing UTF-8/16 to a file you should use std::codecvt_utf16 or std::codecvt_utf8_utf16 as follow:

std::wofstream WFile("file.txt");
if (!WFile.is_open()) return false;
WFile.imbue(std::locale(WFile.getloc(), new std::codecvt_utf16<az::cChar, 0x10ffff, std::little_endian>()));
WFile << (wchar_t)0xfeff;
WFile << L"日本語|भारतीय|русский язык|";
WFile.close();

Currently, std::codecvt_utf16 and std::codecvt_utf8_utf16 have been deprecated, so, what the alternative to make the output stream to write UTF-8/16?

Lion King
  • 32,851
  • 25
  • 81
  • 143
  • 3
    Related: [Deprecated header replacement](https://stackoverflow.com/questions/42946335/deprecated-header-codecvt-replacement). And from the [C++17 changes](https://isocpp.org/files/papers/p0636r0.html): "*Users should use dedicated text-processing libraries instead.*". – dxiv Jul 11 '20 at 16:43
  • Your code is not related to UTF8. By the way, UTF8 is preferred over UTF16. Windows programs also prefer using UTF8 for saving files and networking. Just convert UTF16 to UTF8 and save it using `std::ofstream`. – Barmak Shemirani Jul 12 '20 at 01:53
  • @BarmakShemirani: That code is just an example but my question generally about using `std::codecvt_` whether UTF-16 or UTF-8. – Lion King Jul 12 '20 at 02:28
  • You don't need `codecvt_` for UTF8. Just use `std::ofstream("file.txt") << u8"日本語..."`. In Windows however, you will need to convert UTF16 to UTF8 before saving file, which takes you back to `codecvt` and deprecation. Also note, Note that `wchar_t` refers to UTF16 in Windows, and UTF32 in Linux. – Barmak Shemirani Jul 12 '20 at 03:28

0 Answers0