Output unicode strings in Windows console app

后端 未结 11 1178
花落未央
花落未央 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 12:06

    SetConsoleCP() and chcp does not the same!

    Take this program snippet:

    SetConsoleCP(65001)  // 65001 = UTF-8
    static const char s[]="tränenüberströmt™\n";
    DWORD slen=lstrlen(s);
    WriteConsoleA(GetStdHandle(STD_OUTPUT_HANDLE),s,slen,&slen,NULL);
    

    The source code must be saved as UTF-8 without BOM (Byte Order Mark; Signature). Then, the Microsoft compiler cl.exe takes the UTF-8 strings as-is.
    If this code is saved with BOM, cl.exe transcodes the string to ANSI (i.e. CP1252), which doesn't match to CP65001 (= UTF-8).

    Change the display font to Lucidia Console, otherwise, UTF-8 output will not work at all.

    • Type: chcp
    • Answer: 850
    • Type: test.exe
    • Answer: tr├ñnen├╝berstr├ÂmtÔäó
    • Type: chcp
    • Answer: 65001 - This setting has changed by SetConsoleCP() but with no useful effect.
    • Type: chcp 65001
    • Type: test.exe
    • Answer: tränenüberströmt™ - All OK now.

    Tested with: German Windows XP SP3

提交回复
热议问题