【发布时间】:2022-01-09 02:03:42
【问题描述】:
在 Windows 10 及更早版本中,我已经能够将本地代码页 1250 中的字符串或使用以下代码的 CP_ACP 成功传输到 UTF-8。但在 Windows 11 中,这不再适用于 CP_ACP(而 1250 仍然有效)。似乎默认代码页现在是 65001,无法通过这种方式转换为 UTF-8。结果简直是假的。
原因可能是,我的例子中的字符串“Öf”没有正确编码为65001。现在我有一个大项目,用户输入字符串,各种第三方扮演角色,似乎都交付1250 中的字符串,或非欧洲用户的当前代码页。
这是为什么呢?又该怎么办?
#include <Windows.h>
#include <cstdio>
int main()
{
printf("UTF Conversation Test\n");
char line[1000];
WCHAR uline[1000];
char uline1[1000];
line[0] = 214;
line[1] = 104;
line[2] = 0;
char *s1 = line;
while (*s1 != 0)
{
printf("%10x %d\n", (int)*s1, (int)*s1);
s1++;
}
printf("\n");
MultiByteToWideChar(1250, 0, line, -1, uline, 1000);
// MultiByteToWideChar(CP_ACP, 0, line, -1, uline, 1000);
WCHAR* s2 = uline;
while (*s2 != 0)
{
printf("%10x %d\n", (int)*s2, (int)*s2);
s2++;
}
printf("\n");
WideCharToMultiByte(CP_UTF8, 0, uline, -1, uline1, 1000, 0, 0);
char *s3 = uline1;
while (*s3 != 0)
{
printf("%10x %d\n", (int)*s3, (int)*s3);
s3++;
}
}
【问题讨论】:
-
这能回答你的问题吗? Is codepage 65001 and utf-8 the same thing?
-
printf("%d\n", GetACP())报告什么? -
CP_ACP表示“使用本地编码”,这取决于 Windows 的本地化。 65001 是 UTF-8,而 Windows 11 显然更改了默认值(最后 ????)。如果您知道它是以这种方式编码的,请使用1250。明确。 -
您的示例
char[]数组专门使用 Windows-1250 中的字符,因此永远使用CP_ACP将此类数据转换为 UTF- 没有意义16,由于CP_ACP不保证映射到代码页1250。直接使用代码页1250是正确的解决方案。仅在处理从用户处获得的文本时使用CP_ACP,即通过在 ANSI 模式下运行的 UI 控件(在这种情况下,您确实应该使用 UNICODE 模式)。代码页 65001 (CP_UTF8) 是 Microsoft 的 UTF-8 代码页,因此如果char[]数据以 UTF-8 开头,则无需通过MultiByteToWideChar()进行转换
标签: winapi utf-8 codepages windows-11