首页 > 解决方案 > 如何将 UTF-8 字符串写入 Windows 控制台?

问题描述

在 win32 api 中,我可以通过将标准输出模式设置为 _O_U16TEXT 并使用 wprintf 来显示 unicode。但是如何使用 printf 将 UTF-8 字符串写入控制台?

当我使用 _setmode 将 stdout 设置为 _O_U8TEXT 时,它抛出了一个断言错误: 断言错误

我还尝试将控制台输出代码页设置为 UTF-8,字符被问号替换:在此处输入图像描述

代码:

#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");
}

标签: cwinapiutf-8console

解决方案


当我使用 _setmode 将 stdout 设置为 _O_U8TEXT 时,它抛出了一个断言错误

printf当前不支持输出到UNICODE流中。改为使用wprintf

您可以尝试以下代码,看看是否有帮助:

//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");

在此处输入图像描述

请参阅代码页标识符SetConsoleOutputCP_setmode


推荐阅读