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

以你之姓@ 2022-10-14 11:00 290阅读 0赞

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

完整代码如下:

  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. class Student
  4. {
  5. char num[11];
  6. char name[20];
  7. int score;
  8. public:
  9. friend istream& operator >> (istream&, Student&);
  10. friend ostream& operator << (ostream&, Student&);
  11. int GetScore()
  12. {
  13. return score;
  14. }
  15. };
  16. istream& operator >> (istream &in, Student &s)
  17. {
  18. cout<<"请输入学生信息:"<<endl;
  19. cout<<"学号:";
  20. in >> s.num;
  21. cout<<"姓名:";
  22. in >> s.name;
  23. cout<<"成绩:";
  24. in >> s.score;
  25. return in;
  26. }
  27. ostream& operator << (ostream &out, Student &s)
  28. {
  29. out <<"学号:"<<s.num<<endl;
  30. out <<"姓名:"<<s.name<<endl;
  31. out <<"成绩:"<<s.score<<endl;
  32. return out;
  33. }
  34. int main()
  35. {
  36. int ave,i;
  37. char ch;
  38. Student s[20];
  39. for(i=0;i<=2;i++)
  40. {
  41. cin>>s[i];
  42. }
  43. ofstream outfile;
  44. outfile.open("imformation.txt",ios::out);
  45. outfile<<s[0]<<endl;
  46. outfile<<s[1]<<endl;
  47. outfile<<s[2]<<endl;
  48. outfile.close();
  49. ifstream infile;
  50. infile.open("imformation.txt");
  51. if(!infile)
  52. {
  53. cout<<"文本内容为空,无法打开!"<<endl;
  54. exit(1);
  55. }
  56. cout <<"下面输出学生信息:"<<endl;
  57. while(infile.get(ch))
  58. {
  59. cout<<ch;
  60. }
  61. infile.close();
  62. cout<<"平均成绩"<<(s[0].GetScore()+s[1].GetScore()+s[2].GetScore())/3;
  63. }

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

发表评论

表情:
评论列表 (有 0 条评论,290人围观)

还没有评论,来说两句吧...

相关阅读