编程语言
首页 > 编程语言> > c++ 读取TXT文件,中文乱码处理

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;
}

 

标签:TXT,strSrc,szRes,NULL,c++,乱码,CP,include,out
来源: https://www.cnblogs.com/zhaopengpeng/p/13390535.html