请看一下C++流文件读写的简单程序

来源:百度知道 编辑:UC知道 时间:2024/05/26 17:33:27
#include<iostream>
#include<iomanip>
#include<fstream>
using namespace std;

struct student
{
char name[10];
char sex;
int age;
char university[20];
};

int main()
{
student stu,stu1;
ofstream ofs("1.txt",ios::binary);
cin>>stu.name>>stu.sex>>stu.age>>stu.university;
ofs.write((char *)&stu,sizeof(stu));
ofs.close();

ifstream ifs("1.txt",ios::binary);
if(ifs)
{
ifs.read((char *)&stu1,sizeof(stu1));
cout<<stu1.name<<' '<<stu1.sex<<' '<<stu1.age<<' '<<stu1.university<<endl;
}
else
cout<<"error! Can't open the file."<<endl;
cout<<endl;
return 0;
}

输出的结果是正确的,但是文件中的信息是乱码,请问这是怎么回事,应该怎么改正?

你用的是二进制读写read和write,年龄、姓名和学校未赋值的部分会以二进制的形式写到文件中,和内存中的一样,而没有转换成可读的文本形式。二进制的好处是节省存储空间。想不显示乱码,把read和wtite换成格式化输出就行了。

#include<iostream>
#include<iomanip>
#include<fstream>
using namespace std;

struct student
{
char name[10];
char sex;
int age;
char university[20];
};

int main()
{
student stu,stu1;
ofstream ofs("1.txt");
cin>>stu.name>>stu.sex>>stu.age>>stu.university;
ofs<<stu.name<<' '<<stu.sex<<' '<<stu.age<<' '<<stu.university;
ofs.close();

ifstream ifs("1.txt",ios::binary);
if(ifs)
{
ifs>>stu1.name>>stu1.sex>>stu1.age>>stu1.university;
cout<<stu1.name<<' '<<stu1.sex<<' '<<stu1.age<<' '<<stu1.university<<endl;<