如何使getch()返回ë的235而非137?本地化是否影响该函数?
问题解决:让getch()读取ë返回235而非137
问题原因
你的Windows控制台当前使用的是代码页1252(Windows-1252),在这个字符集中,ë的单字节编码是0x89(十进制137);而你期望的235(0xEB)是ISO-8859-1(Latin-1)字符集中ë的编码值。这种差异和你的荷兰语Windows环境直接相关——荷兰语系统默认控制台代码页通常为1252,和美式键盘无关。
解决方案
方案1:切换控制台代码页到ISO-8859-1
通过修改控制台的输入输出代码页,让getch()直接读取到ISO-8859-1编码的数值:
程序内动态切换(推荐)
调用Windows API SetConsoleCP和SetConsoleOutputCP设置代码页为28591(ISO-8859-1的代码页编号):
#include <windows.h> #include <conio.h> #include <stdio.h> int main() { // 设置控制台输入输出代码页为ISO-8859-1 SetConsoleCP(28591); SetConsoleOutputCP(28591); unsigned char c = getch(); printf("读取到的字符值: %u\n", c); // 此时读取ë会返回235 return 0; }
手动切换控制台代码页
在启动程序前,打开控制台执行以下命令:
chcp 28591
再运行你的程序,getch()读取ë时就会返回235。
方案2:直接从当前编码转换为UTF-8(更健壮)
如果你的最终目标是得到ë的UTF-8编码(0xC3 0xAB),无需强行获取235,直接通过系统API完成编码转换更可靠,避免依赖特定代码页:
#include <windows.h> #include <conio.h> #include <stdio.h> #include <stdlib.h> int main() { // 读取Windows-1252编码的字符(ë返回137) unsigned char win1252_char = getch(); // 转换为宽字符 wchar_t wide_char; MultiByteToWideChar(CP_ACP, 0, (char*)&win1252_char, 1, &wide_char, 1); // 转换为UTF-8 char utf8_buf[4]; int utf8_len = WideCharToMultiByte(CP_UTF8, 0, &wide_char, 1, utf8_buf, sizeof(utf8_buf), NULL, NULL); printf("UTF-8编码字节: 0x%X 0x%X\n", (unsigned char)utf8_buf[0], (unsigned char)utf8_buf[1]); // 输出0xC3 0xAB return 0; }
注意事项
getch()是单字节字符集的函数,若需处理Unicode字符,推荐使用宽字符版本_getwch(),搭配wchar_t类型存储。- 硬编码字符数值(如235)不可靠,不同代码页下同一字符的数值差异很大,使用系统API做编码转换是更通用的方案。
内容的提问来源于stack exchange,提问作者Ksm
相关产品推荐
相关产品推荐

