其他分享
首页 > 其他分享> > 1. 文件乱码

1. 文件乱码

作者:互联网

 1 #include<vector>
 2 #include <fstream>
 3 #include <iostream>
 4 #include<string>
 5 #include <Windows.h>
 6 using namespace std;
 7 
 8 string UTF8ToGB(const char* str);
 9 int main()
10 {
11     ifstream in_file;
12     in_file.open("D:\\S\\学习\\C++\\C++Prime_5\\8\\file4\\files1.txt");
13     auto state = in_file.is_open();
14     if (!in_file)
15     {
16         cerr << "文件打开失败" << endl;
17         return -1;
18     }
19     string line;
20     vector<string>lines;
21     while (getline(in_file, line))
22     {
23         line = UTF8ToGB(line.c_str()).c_str();
24         lines.push_back(line);
25     }
26     in_file.close();
27     for (auto p = lines.cbegin(); p != lines.cend(); p++)
28         cout << *p<<endl;
29     return 0;
30 }
31 
32 //此处可以解决乱码
33 string UTF8ToGB(const char* str)
34 {
35     string result;
36     WCHAR* strSrc;
37     LPSTR szRes;
38 
39     //获得临时变量的大小
40     int i = MultiByteToWideChar(CP_UTF8, 0, str, -1, NULL, 0);
41     strSrc = new WCHAR[i + 1];
42     MultiByteToWideChar(CP_UTF8, 0, str, -1, strSrc, i);
43 
44     //获得临时变量的大小
45     i = WideCharToMultiByte(CP_ACP, 0, strSrc, -1, NULL, 0, NULL, NULL);
46     szRes = new CHAR[i + 1];
47     WideCharToMultiByte(CP_ACP, 0, strSrc, -1, szRes, i, NULL, NULL);
48 
49     result = szRes;
50     delete[]strSrc;
51     delete[]szRes;
52 
53     return result;
54 }

 

标签:文件,str,lines,乱码,file,line,include,UTF8ToGB
来源: https://www.cnblogs.com/xingyuanzier/p/16412559.html