1. 文件乱码

2022/6/25 23:30:58

本文主要是介绍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 }

 



这篇关于1. 文件乱码的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程