WriteConsoleW, wprintf and Unicode

后端 未结 2 628
情歌与酒
情歌与酒 2021-01-03 08:57
AllocConsole();
consoleHandle = GetStdHandle(STD_OUTPUT_HANDLE);
WriteConsoleW(consoleHandle, L\"qweąęėšų\\n\", 9, NULL, NULL);
_wfreopen(L\"CONOUT$\", L\"w\", stdou         


        
相关标签:
2条回答
  • 2021-01-03 09:01

    At first I accepted Hans Passant answer, but the root cause for wprintf not printing to UTF-8 streams is that wprintf behaves as though it uses the function wcrtomb, which encodes a wide character (wchar_t) into a multibyte sequence, depending on the current locale - link. Windows does not have an UTF-8 capable locale (a locale which would support an UTF-8 codepage (65001)).

    Quote from MSDN:

    The set of available locale names, languages, country/region codes, and code pages includes all those supported by the Windows NLS API except code pages that require more than two bytes per character, such as UTF-7 and UTF-8.

    0 讨论(0)
  • 2021-01-03 09:06

    The stdout stream can be redirected and therefore always operates in 8-bit mode. The Unicode string you pass to wprintf() gets converted from utf-16 to the 8-bit code page that's selected for the console. By default that's the olden 437 OEM code page. That's where the buck stops, that code page doesn't support the character.

    You'll need to switch to another 8-bit code page, one that does support that character. A good choice is 65001, the code page for utf-8. Fix:

     SetConsoleOutputCP(CP_UTF8);
    

    Or use SetConsoleCP() if you want stdin to use utf-8 as well.

    0 讨论(0)
提交回复
热议问题