写文件
#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();
}
读文件并转码
#include <fstream>
#include <iostream>
#include <Windows.h>
#include <string>
using namespace std; string UTF8ToGB(const char* str)
{
string result;
WCHAR *strSrc;
LPSTR szRes; //获得临时变量的大小
int i = MultiByteToWideChar(CP_UTF8, , str, -, NULL, );
strSrc = new WCHAR[i+];
MultiByteToWideChar(CP_UTF8, , str, -, strSrc, i); //获得临时变量的大小
i = WideCharToMultiByte(CP_ACP, , strSrc, -, NULL, , NULL, NULL);
szRes = new CHAR[i+];
WideCharToMultiByte(CP_ACP, , strSrc, -, szRes, i, NULL, NULL); result = szRes;
delete []strSrc;
delete []szRes; return result;
} int main()
{
char txt[];
string msg;
ifstream infile;
infile.open("1.txt"); if(!infile.is_open())
{
cout<<""<<endl;
exit();
} while(!infile.eof())
{
infile.getline(txt,);
msg=UTF8ToGB(txt);
cout<<msg<<endl; } infile.close();
getchar();
}
C++中文乱码解决
#include<iostream>
#include <string>
#include <Windows.h>
using namespace std;
string UTF8ToGB(const char* str)
{
string result;
WCHAR *strSrc;
LPSTR szRes; //获得临时变量的大小
int i = MultiByteToWideChar(CP_UTF8, , str, -, NULL, );
strSrc = new WCHAR[i+];
MultiByteToWideChar(CP_UTF8, , str, -, strSrc, i); //获得临时变量的大小
i = WideCharToMultiByte(CP_ACP, , strSrc, -, NULL, , NULL, NULL);
szRes = new CHAR[i+];
WideCharToMultiByte(CP_ACP, , strSrc, -, szRes, i, NULL, NULL); result = szRes;
delete []strSrc;
delete []szRes; return result;
} string msg; int main ()
{
const char txt[] = "哈哈哈";
msg=UTF8ToGB(txt);
cout<<msg<<endl; return ;
}