[英]How do I print Unicode to the output console in C with Visual Studio?
正如问题所说,我必须做什么才能将 Unicode 字符打印到输出控制台? 我必须使用哪些设置? 现在我有这个代码:
wchar_t* text = L"the 来";
wprintf(L"Text is %s.\n", text);
return EXIT_SUCCESS;
它打印: Text is the ?.
我尝试将输出控制台的字体更改为 MS Mincho、Lucida Console 和其他一些字体,但它们仍然不显示日文字符。
那么,我该怎么办?
这是对我有用的代码 (VS2017) - 启用 Unicode 的项目
#include <stdio.h>
#include <io.h>
#include <fcntl.h>
int main()
{
_setmode(_fileno(stdout), _O_U16TEXT);
wchar_t * test = L"the 来. Testing unicode -- English -- Ελληνικά -- Español." ;
wprintf(L"%s\n", test);
}
这是控制台
将其复制到 Notepad++ 后,我看到了正确的字符串
来。 测试 unicode -- 英语 -- Ελληνικά -- 西班牙语。
操作系统 - Windows 7 英文,控制台字体 - Lucida 控制台
我试图修复上面的代码以在 Windows 10 上与 VS2019 一起工作,我能想到的最好的就是这个
#include <stdio.h>
int main()
{
const auto* test = L"the 来. Testing unicode -- English -- Ελληνικά -- Español.";
wprintf(L"%s\n", test);
}
当它在控制台设置为喜欢 Lucida Console 和 UTF-8 编码的情况下运行时,我看到
作为显示为空矩形的来字符的答案 - 我想是不包含所有 Unicode gliphs 的字体的限制
当文本从最后一个控制台复制到 Notepad++ 时,所有字符都正确显示
问号通常表示 Windows 无法将字符转换为目标代码页。 在控制台中,空心方块表示 Unicode 字符已正确接收但无法显示,因为控制台字体不支持它,或者它是一个需要 Uniscribe 的复杂脚本,控制台无法处理。 您可以复制正方形并将其粘贴到记事本/写字板中,它应该可以正确显示。
WriteConsoleW
Windows 函数可以显示 Unicode 字符,并且可以一直工作到 Windows NT。 它只能写入控制台,因此在重定向输出时必须改用WriteFile
。 GetConsoleMode
在重定向句柄上失败。
你没有说你使用的是哪个 VS 版本,而且这些年来情况发生了变化,但是如果你调用_setmode(_fileno(stdout), _O_U16TEXT);
Unicode 输出自 VS2005 以来一直不错_setmode(_fileno(stdout), _O_U16TEXT);
在 main() 早期:
#include <stdio.h>
#include <io.h>
#include <fcntl.h>
int main()
{
_setmode(_fileno(stdout), _O_U16TEXT); // Call this before writing anything
wchar_t * test = L"the 来" ;
wprintf(L"Text is %s.\n", test);
return 0;
}
另请参阅: 控制台中的神话破坏
字符“来”可能不在您的系统字符代码页中。 您需要将字符保存为 utf-8。
在 vs2013 中,我试试这个:
// save as utf-8
#pragma execution_character_set( "utf-8" )
#include <Windows.h>
char *s = "the 来";
int main(){
// set console code page to utf-8
SetConsoleOutputCP(65001);
printf("%s\n",s);
return 0;
}
这对我有用:
#include <locale.h>
在主函数中,
setlocale(LC_ALL, "en_US.UTF-8");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.