c++中使用ifstream,ofstream,fstream实现对文件的读写操作,总是遇到乱码问题,
下面两个实例,解决乱码问题。
实例一:
//我们可以使所有的数组初始化为0,文件读取时,当读取到0时,就会停止读取!
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main()
{
char name1[100]={0};
char name2[100]={0};
ofstream w;
w.open("text.txt");
if(!w.is_open())
{
cerr<<"write file open error"<<endl;
}
cin>>name1;
w.write(name1,sizeof(name1));
w.close();
ifstream r;
r.open("text.txt");
if(!r.is_open())
{
cerr<<"read file open error"<<endl;
}
r.read(name2,sizeof(name2));
cout<<name2<<endl;
r.close();
}
实例二:
// \0作为字符串的结尾,我们可以使写入的内容,最后一个赋值为\0.
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main()
{
const int num=100;
char name1[num];
string str;
cin>>str;
int length=str.size();
length=length<num?length:num-1;
str.copy(name1,length);
name1[length]='\0';
ofstream w;
w.open("text.txt");
if(!w.is_open())
{
cerr<<"write file open error"<<endl;
}
w.write(name1,sizeof(name1));
w.close();
ifstream r;
r.open("text.txt");
if(!r.is_open())
{
cerr<<"read file open error"<<endl;
}
char name2[num];
r.read(name2,sizeof(name2));
cout<<name2<<endl;
r.close();
}