c - 如何将 UTF-8 字符串写入 Windows 控制台?

标签 c winapi utf-8 console

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

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

我还尝试将控制台输出代码页设置为 UTF-8,字符被替换为问号:enter image description here

代码:

#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 当前不支持输出到 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");

enter image description here

引用 Code Page Identifiers , SetConsoleOutputCP_setmode .

关于c - 如何将 UTF-8 字符串写入 Windows 控制台?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59545262/

相关文章:

c - 在 header 中发现函数的隐式声明?

c - 在英特尔 x64 汇编中执行函数的最快(CPU 方式)方式?

delphi - 当迭代表单上的控件时,如何识别特定按钮?

winapi - 不在偏移量 0 处映射 Win32 可移植可执行镜像的可能原因是什么?

php使用utf8导出到excel

c++ - 将 Rcpp 与 C 代码链接起来以进行自适应大都会拒绝采样

javascript - C 中的 IsNan 等价物

c++ - C++ 流的flush() 和FindFirstFileEx() 之间的竞争条件

用于将 UTF-8 转换为 ASCII 的 Python 脚本

Python 读取带有希伯来文标题的 csv