1. 程式人生 > >c++ 讀檔案,讀取到中文如果是亂碼的處理方式。

c++ 讀檔案,讀取到中文如果是亂碼的處理方式。

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