1

I'm trying to write Japanese to a file using wofstream and wstring. Unfortunately, wofstream doesn't write Japanese characters to the file when compiled with g++ or clang++ (in WSL and Windows 10) with no additional flags.

#include <fstream>

int main() {
    std::wofstream file("file.txt");
    std::wstring str = L"Onee-chan, Ohayou!";
    file << str;
}

file.txt

Onee-chan, Ohayou!

But,

#include <fstream>

int main() {
    std::wofstream file("file.txt");
    std::wstring str = L"お姉ちゃん、おはよう!";
    file << str;
}

file.txt has 0 bytes of size.

BUT when compiled with MSVC with the following code,

#include <fstream>

int main() {
    std::ofstream file("file.txt");
    std::string str = "お姉ちゃん、おはよう!";
    file << str;
}

file.txt has:
お姉ちゃん、おはよう!

Want my application to run on both linux and Windows. It works on windows with msvc (using string, char and fstreams [that's good]). I don't think MSVC is on linux, therefore I tried using wstring, wchat_t and wfstreams with g++ (in WSL and Windows cmd) but they don't write Japanese to the files.

Any suggestions on how to get through this.

(For Example: msvc like settings for g++(preferred) or any changes in the code(not preferred))

Someone
  • 126
  • 8
  • Adding `std::locale::global(std::locale(""));` at the start of `main` fixed it for me. So does `file.imbue(std::locale(""));` (after you define `file` of course). – mediocrevegetable1 Sep 28 '21 at 05:36
  • Your code works as is for me on windows `g++ (Rev9, Built by MSYS2 project) 10.2.0` – infinitezero Sep 28 '21 at 05:38
  • Does this have to be using wide strings with GCC? Making everything UTF-8 and using a regular `std::string` (or something that actually conveys that info) seems like the more workable option. – chris Sep 28 '21 at 05:41
  • AFAIK [`std::wstring` is not the Unicode string in Linux](https://stackoverflow.com/a/32413257/8423261), try using `std::string` and `std::ofstream` instead and see if that makes a change. – Ruks Sep 28 '21 at 05:47

0 Answers0