简体   繁体   English

如何更改控制台程序以在 Windows 中支持 unicode?

[英]How to change console program for unicode support in windows?

The following program can be compiled using msvc or mingw.可以使用 msvc 或 mingw 编译以下程序。 However, the mingw version cannot display unicode correctly.但是,mingw 版本无法正确显示 unicode。 Why?为什么? How can I fix that?我该如何解决?

Code:代码:

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

int wmain(void)
{
    _setmode(_fileno(stdout), _O_U16TEXT);
    _putws(L"哈哈哈");
    system("pause");

    return 0;
}

Mingw64 Compile Command: Mingw64 编译命令:
i686-w64-mingw32-gcc -mconsole -municode play.c

MSVC Compiled: MSVC 编译:
在此处输入图片说明

Mingw Compiled: Mingw编译:
在此处输入图片说明

Edit:编辑:
After some testing, the problem seems not causing by mingw.经过一些测试,问题似乎不是由 mingw 引起的。 If I run the program directly by double clicking the app.如果我通过双击应用程序直接运行程序。 The unicode string cannot be displayed correct either. unicode 字符串也无法正确显示。 The code page however, is the same, 437.然而,代码页是相同的,437。

It turns out the problem is related to console font instead of the compiler.事实证明,问题与控制台字体有关,而不是与编译器有关。 See the following demo code for changing console font.请参阅以下演示代码以更改控制台字体。

After doing some research, it turns out the default console font does not support chainese glyphs.经过一些研究,事实证明默认的控制台字体不支持 chainese 字形。 One can change the console font by using SetCurrentConsoleFontEx function.可以使用SetCurrentConsoleFontEx函数更改控制台字体。

Demo Code:演示代码:

#ifdef _MSC_VER
#define _CRT_SECURE_NO_WARNINGS
#endif

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

#define FF_SIMHEI 54

int main(int argc, char const *argv[])
{
    CONSOLE_FONT_INFOEX cfi = {0};

    cfi.cbSize = sizeof(CONSOLE_FONT_INFOEX);
    cfi.nFont = 0;
    cfi.dwFontSize.X = 8;
    cfi.dwFontSize.Y = 16;
    cfi.FontFamily = FF_SIMHEI;
    cfi.FontWeight = FW_NORMAL;
    wcscpy(cfi.FaceName, L"SimHei");

    SetCurrentConsoleFontEx(GetStdHandle(STD_OUTPUT_HANDLE), FALSE, &cfi);

    /* UTF-8 String */
    SetConsoleOutputCP(CP_UTF8); /* Thanks for Eryk Sun's notice: Remove this line if you are using windows 7 or 8 */
    puts(u8"UTF-8你好");

    /* UTF-16 String */
    _setmode(_fileno(stdout), _O_U16TEXT);
    _putws(L"UTF-16你好");

    system("pause");

    return 0;
}

This is happening because of missing #define UNICODE & #define _UNICODE .这是因为缺少#define UNICODE & #define _UNICODE You should try adding it along with other headers.您应该尝试将其与其他标题一起添加。 The _UNICODE symbol is used with headers such as tchar.h to direct standard C functions such as printf() and fopen() to the Unicode versions. _UNICODE 符号与头文件(例如 tchar.h)一起使用,以将标准 C 函数(例如 printf() 和 fopen())定向到 Unicode 版本。

Please Note - The -municode option is still required when linking if Unicode mode is used.请注意 - 如果使用 Unicode 模式,链接时仍然需要 -municode 选项。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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