C语言控制台编码不匹配问题:如何统一为Windows-1251?
如何在C语言程序中统一输入输出为Windows-1251编码解决西里尔字符显示问题
我编写的C语言程序旨在获取一个字符并立即显示,但输入为CP866编码、输出为Windows-1251编码,导致西里尔字符显示异常或无输出。尝试使用wchar_t、wprintf()、getwchar()后问题仍未解决,求将输入输出统一为Windows-1251编码的方法。原程序代码如下:
#include <stdio.h> #include <stdlib.h> #include <locale.h> int main(void) { setlocale(LC_ALL, ""); printf("Уведіть символ.\n"); char ch = getchar(); printf("\n"); printf("%c", ch); getchar(); getchar(); return 0; }
解决方案
要强制Windows环境下的输入输出统一使用Windows-1251编码,需要明确指定对应locale,同时通过系统API锁定控制台的输入输出代码页,具体步骤如下:
1. 指定Windows-1251对应的Locale
Windows中Windows-1251编码对应的Locale名称可以是Russian_Russia.1251或Ukrainian_Ukraine.1251(两者均支持西里尔字符,后者匹配原程序中的乌克兰语文本),直接用setlocale指定该值,替代默认的空字符串(空字符串会调用系统默认Locale,可能不符合需求)。
2. 设置控制台代码页
调用Windows API SetConsoleCP设置输入代码页,SetConsoleOutputCP设置输出代码页,Windows-1251对应的代码页编号是1251,需要引入<windows.h>头文件。
修改后的单字节字符版本代码
#include <stdio.h> #include <stdlib.h> #include <locale.h> #include <windows.h> int main(void) { // 设置Locale为Windows-1251 if (!setlocale(LC_ALL, "Ukrainian_Ukraine.1251")) { fprintf(stderr, "无法设置指定Locale\n"); return 1; } // 锁定控制台输入输出代码页为1251 SetConsoleCP(1251); SetConsoleOutputCP(1251); printf("Уведіть символ.\n"); char ch = getchar(); printf("\n%c", ch); getchar(); getchar(); return 0; }
宽字符版本补充(若需使用wchar_t)
如果坚持使用宽字符类型,只需替换对应的输入输出函数,同时保持Locale和代码页设置不变:
#include <stdio.h> #include <stdlib.h> #include <locale.h> #include <windows.h> int main(void) { if (!setlocale(LC_ALL, "Ukrainian_Ukraine.1251")) { fwprintf(stderr, L"无法设置指定Locale\n"); return 1; } SetConsoleCP(1251); SetConsoleOutputCP(1251); wprintf(L"Уведіть символ.\n"); wchar_t ch = getwchar(); wprintf(L"\n%lc", ch); getwchar(); getwchar(); return 0; }
内容的提问来源于stack exchange,提问作者GreenElephant
相关产品推荐
相关产品推荐

