c++编码及读写文件
写文件
#include <fstream> #include <iostream> using namespace std; int main() { ofstream outfile("1.txt",ios::ate); //打开文件,设置写入方式为覆盖写入 if(!outfile) { cout<<"txt文件打开失败!"<<endl; exit(0); } outfile<<"写入txt文件示例.\n"; outfile<<"成功写入.\n"; outfile.close(); }
读文件并转码
1 #include <fstream> 2 #include <iostream> 3 #include <Windows.h> 4 #include <string> 5 using namespace std; 6 7 string UTF8ToGB(const char* str) 8 { 9 string result; 10 WCHAR *strSrc; 11 LPSTR szRes; 12 13 //获得临时变量的大小 14 int i = MultiByteToWideChar(CP_UTF8, 0, str, -1, NULL, 0); 15 strSrc = new WCHAR[i+1]; 16 MultiByteToWideChar(CP_UTF8, 0, str, -1, strSrc, i); 17 18 //获得临时变量的大小 19 i = WideCharToMultiByte(CP_ACP, 0, strSrc, -1, NULL, 0, NULL, NULL); 20 szRes = new CHAR[i+1]; 21 WideCharToMultiByte(CP_ACP, 0, strSrc, -1, szRes, i, NULL, NULL); 22 23 result = szRes; 24 delete []strSrc; 25 delete []szRes; 26 27 return result; 28 } 29 30 int main() 31 { 32 char txt[100]; 33 string msg; 34 ifstream infile; 35 infile.open("1.txt"); 36 37 if(!infile.is_open()) 38 { 39 cout<<""<<endl; 40 exit(0); 41 } 42 43 while(!infile.eof()) 44 { 45 infile.getline(txt,100); 46 msg=UTF8ToGB(txt); 47 cout<<msg<<endl; 48 49 } 50 51 infile.close(); 52 getchar(); 53 }
C++中文乱码解决
1 #include<iostream> 2 #include <string> 3 #include <Windows.h> 4 using namespace std; 5 string UTF8ToGB(const char* str) 6 { 7 string result; 8 WCHAR *strSrc; 9 LPSTR szRes; 10 11 //获得临时变量的大小 12 int i = MultiByteToWideChar(CP_UTF8, 0, str, -1, NULL, 0); 13 strSrc = new WCHAR[i+1]; 14 MultiByteToWideChar(CP_UTF8, 0, str, -1, strSrc, i); 15 16 //获得临时变量的大小 17 i = WideCharToMultiByte(CP_ACP, 0, strSrc, -1, NULL, 0, NULL, NULL); 18 szRes = new CHAR[i+1]; 19 WideCharToMultiByte(CP_ACP, 0, strSrc, -1, szRes, i, NULL, NULL); 20 21 result = szRes; 22 delete []strSrc; 23 delete []szRes; 24 25 return result; 26 } 27 28 string msg; 29 30 int main () 31 { 32 const char txt[10] = "哈哈哈"; 33 msg=UTF8ToGB(txt); 34 cout<<msg<<endl; 35 36 return 0; 37 }
你要觉得这篇文章比较好,记得点推荐!