MingW64如何输入UTF-8字符?

问题描述 投票:0回答:1
Platform: Windows x64 22H2

我有以下代码(文件编码格式:UTF-8):

#include <stdio.h>

int main(int argc, char **argv)
{
    static char text[8];
    scanf("%[^\n]s", text);
    printf("%s\n", text);
    return 0;
}

仅输入ASCII表中的字符即可正常工作
但是当输入中文或其他Unicode编码等字符时,就读不出来

若输入Unicode字符,则文本数组内容为:

00 00 00 00 00 00 00 00
。 我在
Windows CMD
中执行了这个程序,编译指令为:
gcc main.c -o main.exe
.

我正在尝试添加本地支持,这是修改后的代码:

#include <stdio.h>
#include <locale.h>

int main(int argc, char **argv)
{
    setlocale(LC_ALL, "zh_CN.UTF-8");
    static char text[8];
    scanf("%[^\n]s", text);
    printf("%s\n", text);
    return 0;
}

但是这个数组的内容还是:

00 00 00 00 00 00 00 00
.

再次尝试将CMD的页码改为65001

(chcp 65001)
,结果还是一样。 我也试过加gcc命令行参数
-finput-charset=UTF-8
,还是不行

但是当我修改代码文件为GB系列的编码(比如GB2312)或者将CMD的页码改为936时,可以正常读取GB2312编码的数据,如下:

input: 你好
output: ce d2 b5 c4 00 00 00 00

这可以读取 Unicode 字符,但不能读取 UTF-8 编码。

c windows utf-8 mingw mingw-w64
1个回答
1
投票

试试?

#include <wchar.h>

int main()
{
    static wchar_t text[32];
    wscanf(L"%ls", text);
    wprintf(L"%ls\n", text);

    return 0;
}
© www.soinside.com 2019 - 2024. All rights reserved.