Output unicode strings in Windows console app

后端 未结 11 941
花落未央
花落未央 2020-11-21 11:20

Hi I was trying to output unicode string to a console with iostreams and failed.

I found this: Using unicode font in c++ console app and this snippet work

11条回答
  •  野的像风
    2020-11-21 11:52

    There are a few issues with the mswcrt and io streams.

    1. Trick _setmode(_fileno(stdout), _O_U16TEXT); working only for MS VC++ not MinGW-GCC. Moreover sometimes it is brings to crashes depending on Windows configuration.
    2. SetConsoleCP(65001) for UTF-8. May fail in many multibyte character scenarios, but is is always OK for UTF-16LE
    3. You need to restore previews console codepage on application exit.

    Windows console supports UNICODE with the ReadConsole and WriteConsole functions in UTF-16LE mode. Background effect - piping in this case will not work. I.e. myapp.exe >> ret.log brings to 0 byte ret.log file. If you are ok with this fact you can try my library as following.

    const char* umessage = "Hello!\nПривет!\nПривіт!\nΧαιρετίσματα!\nHelló!\nHallå!\n";
    
    ...
    #include 
    #include 
    ...
    
    std::ostream& cout = io::console::out_stream();
    cout << umessage
    << 1234567890ull << '\n'
    << 123456.78e+09 << '\n'
    << 12356.789e+10L << '\n'
    << std::hex << 0xCAFEBABE
    << std::endl;
    

    Library will auto-convert your UTF-8 into UTF-16LE and write it into console using WriteConsole. As well as there are error and input streams. Another library benefit - colors.

    Link on example app: https://github.com/incoder1/IO/tree/master/examples/iostreams

    The library homepage: https://github.com/incoder1/IO

    Screenshot:

提交回复
热议问题