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

C++读取含特殊字符的文件到字符串乱码问题求解

解决C++读取含特殊字符文本文件的乱码问题

问题根源

你遇到的乱码是因为文件编码与程序读取/输出的编码不匹配:

  • 开头的∩╗┐是UTF-8 BOM(字节顺序标记,0xEF 0xBB 0xBF)被本地编码(如GBK)解析的结果
  • 长破折号—的UTF-8编码是0xE2 0x80 0x94,被本地编码解析成了ΓÇö
  • 用wifstream无效,是因为没有指定正确的编码转换规则,默认还是用本地编码处理。

解决方案

方案1:指定UTF-8编码读取(跨平台,C++11+)

使用std::wifstream配合std::codecvt_utf8读取UTF-8编码文件,同时处理可能存在的BOM:

#include <iostream>
#include <string>
#include <fstream>
#include <locale>
#include <codecvt>

int main()
{
    std::wifstream test("Pontaje.txt");
    if (!test.is_open()) {
        std::cerr << "无法打开文件" << std::endl;
        return 1;
    }

    // 跳过UTF-8 BOM(如果存在)
    if (test.peek() == 0xFEFF) {
        test.get();
    }

    // 设置UTF-8编码转换规则
    test.imbue(std::locale(test.getloc(), new std::codecvt_utf8<wchar_t>));

    std::wstring test2;
    std::getline(test, test2);

    // 输出宽字符内容
    std::wcout << test2 << std::endl;

    return 0;
}

方案2:Windows平台下直接适配控制台编码

Windows环境中,可将控制台输入输出编码设置为UTF-8,用普通ifstream读取即可(UTF-8单字节兼容,只要输出编码匹配):

#include <iostream>
#include <string>
#include <fstream>
#include <windows.h>

int main()
{
    // 设置控制台输入输出为UTF-8编码
    SetConsoleOutputCP(CP_UTF8);
    SetConsoleCP(CP_UTF8);

    std::ifstream test("Pontaje.txt");
    if (!test.is_open()) {
        std::cerr << "无法打开文件" << std::endl;
        return 1;
    }

    // 检测并跳过UTF-8 BOM
    char bom[3];
    test.read(bom, 3);
    if (!(bom[0] == (char)0xEF && bom[1] == (char)0xBB && bom[2] == (char)0xBF)) {
        // 若不是BOM,将文件指针移回开头
        test.seekg(0);
    }

    std::string test2;
    std::getline(test, test2);

    std::cout << test2 << std::endl;

    return 0;
}

额外注意事项

  • 确认文本编辑器保存文件时使用UTF-8编码(带或不带BOM均可,代码已处理BOM情况)
  • 若控制台仍乱码,需更换支持UTF-8的字体(如Consolas、微软雅黑)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 08:30:45