【C++输入输出流】从键盘输入若干学生信息,写入文本文件中

从键盘输入若干学生信息,写入文本文件中,再从该文本文件中读出学生的信息。
具体要求如下:
(1)应定义学生类Student,成员数据包括学号、姓名和成绩等;
(2)建议用友元函数为学生类重载输入输出流的<<和>>运算符,实现学生信息的整体输入输出功能;例如:
friend istream& operator >> (istream&, Student&);
friend ostream& operator << (ostream&, Student&);
(3) 要求在主函数中,从键盘输入多个学生的信息
(4) 要求将全部学生信息存入文本文件中;
(5) 最后从文件中读出全部学生信息显示到屏幕上,并求平均成绩。

完整代码如下:

#include <bits/stdc++.h>
using namespace std;
class Student
{
	char num[11];
	char name[20];
	int score;
public:
	friend istream& operator >> (istream&, Student&); 
	friend ostream& operator << (ostream&, Student&); 
	int GetScore()
	{
		return score;
	}
};
istream& operator >> (istream &in, Student &s)
{
	cout<<"请输入学生信息:"<<endl;
	cout<<"学号:";
	in >> s.num;
	cout<<"姓名:";
	in >> s.name;
	cout<<"成绩:";
	in >> s.score;
	return in; 
}
ostream& operator << (ostream &out, Student &s)
{
	out <<"学号:"<<s.num<<endl; 
	out <<"姓名:"<<s.name<<endl;
	out <<"成绩:"<<s.score<<endl;
	return out;
}
int main()
{
	int ave,i;
	char ch;
	Student s[20];
	for(i=0;i<=2;i++)
	{
		cin>>s[i];
	} 
	ofstream outfile;
	outfile.open("imformation.txt",ios::out);
	outfile<<s[0]<<endl;
	outfile<<s[1]<<endl;
	outfile<<s[2]<<endl;
	outfile.close();
	
	ifstream infile;
	infile.open("imformation.txt");
	if(!infile)
	{
		cout<<"文本内容为空,无法打开!"<<endl;
		exit(1);
	}
	cout <<"下面输出学生信息:"<<endl;
	while(infile.get(ch))
	{
		cout<<ch;
	}
	infile.close();
	cout<<"平均成绩"<<(s[0].GetScore()+s[1].GetScore()+s[2].GetScore())/3;
}

运行示例:
在这里插入图片描述
在这里插入图片描述

  • 8
    点赞
  • 68
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值