c++ 读取TXT文件,中文乱码处理

180it 2020-10-09 PM 2576℃ 0条

c++ 读取TXT文件,中文乱码处理

#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <windows.h>
 
using namespace std;
 
 
string UTF8ToGB(const char* str)
{
    string result;
    WCHAR *strSrc;
    LPSTR szRes;
 
    //获得临时变量的大小
    int i = MultiByteToWideChar(CP_UTF8, 0, str, -1, NULL, 0);
    strSrc = new WCHAR[i + 1];
    MultiByteToWideChar(CP_UTF8, 0, str, -1, strSrc, i);
 
    //获得临时变量的大小
    i = WideCharToMultiByte(CP_ACP, 0, strSrc, -1, NULL, 0, NULL, NULL);
    szRes = new CHAR[i + 1];
    WideCharToMultiByte(CP_ACP, 0, strSrc, -1, szRes, i, NULL, NULL);
 
    result = szRes;
    delete[]strSrc;
    delete[]szRes;
 
    return result;
}
 
int main(int argc, char *argv[])
{
    ifstream in;
    in.open("C:/in.txt");
 
    string s;
    ofstream out;
    out.open("c:/output.txt");
    //getline(t, s);
    //out << s << "\n";
 
    while (std::getline(in, s))
    {
        string str = UTF8ToGB(s.c_str()).c_str();
        //对每一行进行操作。
        out << str << "\n";
 
    }
    out.close();
    in.close();
 
 
    system("pause");
    return 0;
}


支付宝打赏支付宝打赏 微信打赏微信打赏

如果文章或资源对您有帮助,欢迎打赏作者。一路走来,感谢有您!

标签: none

c++ 读取TXT文件,中文乱码处理