gpt4 book ai didi

C - 字符未在输出中正确显示

转载 作者:太空狗 更新时间:2023-10-29 16:10:03 25 4
gpt4 key购买 nike

我可以在我的源代码中插入 è 字符,但是这在我的程序的输出中没有正确显示; Þ 字符出现在它的位置。

ASCII Extended中的è字符对应于138

Unicode 中的 è 字符匹配 232 数字。

ASCII Extended中的Þ字符对应232数。

Unicode 中的 Þ 字符匹配 222 数字。

通过调试器可以注意到编译器将 è 转换为数字 232 并将整数 138 转换为字符 Š (Line Tabulation Set),而在输出中,字符编号 232 表示为 Þ,字符编号 138 为表示为 è

幕后发生了什么?

示例代码:

#include <stdio.h>

int main (void)
{
    unsigned char a = 'è';
    unsigned char b = 138;

   printf ("Char a:% c \ n", a);
   printf ("Char a:% d \ n \ n", a);
   printf ("Char b:% c \ n", b);
    printf ("Char b:% d \ n \ n", b);

    return 0;
 }

输出:

Char a: Þ
Char to: 232
    
Char b: 'è'
Char b: 138

调试器看到的内容:

char a = 232 'è'
char b = 138 'Š'

最佳答案

我猜你在 Windows 上。

您的源代码是 Unicode,因此 è 字符被编码为数字 232。编译器在生成的程序中使用该值。

当您的程序执行时,此代码作为参数发送到 printf 函数,但由于 Windows 使用扩展 ASCII,因此在打印时它被解释为 Þ控制台。

您可以使用扩展 ASCII 编码您的文件以获得正确的字符。

要确定您的控制台使用哪种编码,您可以在 Windows 中使用它:

#include <windows.h>
unsigned cp = GetConsoleOutputCP();

你可以用这个改变控制台编码:

#include <windows.h>
SetConsoleOutputCP(1252); //Set console encoding to Windows 1252
SetConsoleOutputCP(65001); //Set console encoding to utf8

这会设置控制台输出而不是控制台输入,所以如果你需要处理扩展的 ASCII 用户输入,你需要使用 GetConsoleCP()SetConsoleCP()设置输入编码。

可以看到其他可用的代码页代码here .

关于C - 字符未在输出中正确显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55002310/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com