c++文件读取中文乱码

c++文件读取中文乱码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<vector>
#include<map>
#include<cstring>
#include<fstream>
#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()
{

ifstream inFile;//输出类
inFile.open("text.txt");//<<,setf(),endl都可以用到这个对象
char line[80];
inFile.getline(line,80);
string msg=UTF8ToGB(line);
cout<<msg;
inFile.close();
}

参考博文:[https://blog.csdn.net/zhancf/article/details/49930969
]