课程设计——输出到TXT

#include "fstream.h"
struct student
{
char name[20];
int num;
int age;
char sex;
};

int main()
{
student stud[3]={"Li",1001,18,'f',"Fun",1002,19,'m',"Wang",1004,17,'f'};
ofstream outfile("stud.dat",ios::binary);//打开文件我这是dat格式的,你可以用txt
if(!outfile)
{
cerr<<"open error!"<<endl;
return 0;
}
for(int i=0;i<3;i++)
outfile.write((char *)&stud[i],sizeof(stud[i]));//写数据到文件中
outfile.close();//关闭流
ifstream infile("stud.dat",ios::binary);//下面是 从 文件中读数据出来。
if(!infile)
{
cerr<<"open error!"<<endl;
return 0;
}
for(int j=0;j<3;j++)
infile.read((char *)&stud[j],sizeof(stud[j]));
for (int k=0;k<3;k++)
{
cout<<"NO."<<k+1<<endl;
cout<<"name:"<<stud[k].name<<endl;
cout<<"num:"<<stud[k].num<<endl;
cout<<"age:"<<stud[k].age<<endl;
cout<<"sex:"<<stud[k].sex<<endl;
}
return 0;
}
原文地址:https://www.cnblogs.com/helloaworld/p/5081947.html