添加链接
link之家
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

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!
#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))

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, 2021 at 5:36 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, 2021 at 5:41 AFAIK std::wstring is not the Unicode string in Linux, try using std::string and std::ofstream instead and see if that makes a change. – Ruks Sep 28, 2021 at 5:47