You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Visual Studio环境下C++控制台突然无法输出西里尔文字符如何解决

问题原因排查
  • 文件编码变更:如果近期修改过in_text.txt的保存编码,比如从原来适配俄语环境的Windows-1251(西里尔文ANSI编码)改为了UTF-8,原有setlocale和1251代码页的配置就会和文件编码不匹配,就会出现你现在看到的多字节拼接乱码。
  • 控制台配置变更:Windows系统更新、终端配置修改后,控制台默认代码页可能从之前的1251变为65001(UTF-8)或者936(中文GBK),和你输出的字符编码不匹配。
  • VS环境配置变更:如果近期升级了Visual Studio版本,或者修改了项目的字符集配置(比如从多字节字符集改为Unicode字符集),也会影响本地化函数的生效逻辑。
修复方案

适配原有Windows-1251编码文件的方案

如果你的in_text.txt还是沿用原来的Windows-1251编码,把注释的两行代码放开,同时调整本地化配置即可:

#include <iostream>
#include <fstream>
#include <string>
#include <Windows.h>
using namespace std;

int main()
{
    setlocale(LC_ALL, "ru-RU");
    SetConsoleCP(1251);
    SetConsoleOutputCP(1251);
    ifstream input{ "in_text.txt" };
    if (!input) {
        cerr << "Error opening file" << endl;
        return 1;
    }
    cout << "Displaying file contents: " << "\n\n";
    string line{};
    while (getline(input, line))
        cout << line << endl;

    input.close();
    return 0;
}

如果运行后还是乱码,右键控制台标题栏→属性→选项,勾选「使用旧版控制台」即可,新版Windows终端对1251这类旧代码页的兼容性存在缺陷。

更通用的长期方案(推荐)

直接统一使用UTF-8编码,不需要依赖俄语本地化配置,适配性更强:

  1. 把in_text.txt另存为UTF-8编码(不带BOM优先,带BOM也可兼容)
  2. 修改代码为如下版本:
#include <iostream>
#include <fstream>
#include <string>
#include <Windows.h>
using namespace std;

int main()
{
    // 直接把控制台输入输出代码页设为UTF-8
    SetConsoleCP(CP_UTF8);
    SetConsoleOutputCP(CP_UTF8);
    ifstream input{ "in_text.txt", ios::binary };
    if (!input) {
        cerr << "Error opening file" << endl;
        return 1;
    }
    cout << "Displaying file contents: " << "\n\n";
    string line{};
    while (getline(input, line))
        cout << line << endl;

    input.close();
    return 0;
}

该方案不需要修改Visual Studio项目的字符集配置,同时也兼容中文、英文等多语言字符输出。

内容的提问来源于stack exchange,提问作者Victor Ajayi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 10:45:03