#文件输入和输出练习题
有一个学生类Student,属性有学号、姓名、成绩。
1.需要从键盘上输入一系列学生类对象,并将这些学生信息写入文件data.txt中。
2.显示文件data.txt中的学生数据和相应的成绩等级
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
using namespace std;
class Student
{
private:
int number;
string name;
double score;
public:
void mark();
friend istream & operator >>(istream &,Student &);
friend ostream & operator <<(ostream &,Student &);
};
void Student::mark()
{
if(score>=90)
cout<<setw(10)<<"优\n";
else if(score>=80)
cout<<setw(10)<<"良\n";
else if(score>=70)
cout<<setw(10)<<"中\n";
else if(score>=60)
cout<<setw(10)<<"及格\n";
else
cout<<setw(10)<<"不及格\n";
}
istream & operator>>(istream & in,Student & s)
{
cout<<"请依次输入学生的学号、姓名、成绩:\n";
in>>s.number>>s.name>>s.score;
return in;
}
ostream & operator<<(ostream & out,Student & s)
{
out<<s.number<<setw(6)<<s.name<<setw(6)<<s.score;
return out;
}
int main()
{
int n;
ofstream fout("/Users/用户名/Desktop/data.txt",ios::out);//Xcode要写明路径
if(!fout)
{
cerr<<"open file error!"<<endl;
exit(1);
}
cout<<"请输入总人数:\n";
cin>>n;
Student *pstu=new Student[n+1];
for(int i=0;i<n;i++)
{
cin>>pstu[i];
}
cout<<"--------------------"<<endl;
for(int i=0;i<n;i++)
{
cout<<pstu[i];
pstu[i].mark();
fout<<pstu[i]<<endl;
}
fout.close();
return 0;
}
输出:
请输入总人数:
3
请依次输入学生的学号、姓名、成绩:
171 Lily 100
请依次输入学生的学号、姓名、成绩:
172 Leo 80
请依次输入学生的学号、姓名、成绩:
173 Amy 70
--------------------
171 Lily 100 优
172 Leo 80 良
173 Amy 70 中
Program ended with exit code: 0
txt文件:
//data.txt
171 Lily 100
172 Leo 80
173 Amy 70