简体   繁体   中英

How to write UTF-8 strings to windows console?

In win32 api I can display unicode by setting stdout mode to _O_U16TEXT and using wprintf. But how can I write UTF-8 strings to console using printf?

When I used _setmode to set stdout to _O_U8TEXT, it threw an assertion error: 断言错误

I also tried to set console output codepage to UTF-8, the character was replaced by question mark: 在此处输入图片说明

Code:

#include <stdio.h>
#include <Windows.h>
#include <io.h>
#include <fcntl.h>

int main(int argc, const char *argv[])
{
    //SetConsoleOutputCP(CP_UTF8);
    //_setmode(_fileno(stdout), _O_U8TEXT);
    printf("你好啊!ABC");
}

When I used _setmode to set stdout to _O_U8TEXT, it threw an assertion error

printf does not currently support output into a UNICODE stream. Use wprintf instead.

You can try the following code to see if it helps:

//Sets the output code page used by the console associated with the calling process.
SetConsoleOutputCP(CP_UTF8); //Unicode (UTF-8)
_setmode(_fileno(stdout), _O_U8TEXT); // _O_U16TEXT / _O_WTEXT

wprintf(L"你好啊!ABC");

在此处输入图片说明

Refer to Code Page Identifiers , SetConsoleOutputCP and _setmode .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM