C++面向对象程序设计课程的作业,初学者,很多地方做的不好,欢迎指正。
题目要求:
创建一个存有学生信息的文本型文件 student_info.txt,包含至少 10 名学生信息,该文件格式如下:
姓名 性别 学号 成绩
Alice F 11位数字学号 90
Bob M 11位数字学号 87
…
定义类 Student,声明非静态私有成员变量:姓名、性别、学号、成绩,声明静态成员变量:学生总人数和总成绩、静态成员函数 get_average,支持计算所有学生的平均成绩。该类需重载<<操作符,支持对 Student 类对象的格式化输出(例如:每个属性域宽 15, 各属性均采用左对齐等)Student 类的其他成员变量、成员函数可按需求自行设计添加。编写一个普通函数 student_info_parser(string file_name, vector<Student> &students),读取student_info.txt,填充存储学生类对象的容器 students。创建主函数文件 main.cpp,测试上述要求功能的正确性。
//此代码段为文件2Students.h
#ifndef _STUDENT_H
#define _STUDENT_H
#include<iostream>
#include<fstream>
#include<string>
#include<cstdlib>
#include<vector>
#include<iomanip>
using namespace std;
class Student
{
public:
Student();
Student(string name,char sex,int number,double score);
static double get_average();//静态成员函数:计算所有学生的平均成绩
friend void student_info_parser(string file_name, vector<Student> &students);
friend ostream & operator<<(ostream &, const Student &);
private:
string name;
char sex;
string number;
double score;
static int totalCount;//静态成员变量:总人数
static double totalScore;//静态成员变量:总成绩
};
#endif
//此代码段为文件2Students.cpp
#include"2Student.h"
using namespace std;
Student::Student(){}
Student::Student(string name,char sex,int number,double score)
{this->name=name;this->sex=sex;this->number=number;this->score=score;}
double Student::get_average()
{return totalScore/totalCount;}
//对静态成员变量进行初始化
int Student::totalCount=0;
double Student::totalScore=0;
//重载<<操作符,对Student类对象的格式化输出(格式:左对齐,姓名、性别、学号、成绩的域宽分别为10,6,15,8)
ostream & operator<<(ostream &os, const Student &stu)
{
os<<setiosflags(ios::left)<<setw(10)<<stu.name<<' '<<setw(6)<<stu.sex<<' '
<<setw(15)<<stu.number<<' '<<setw(8)<<stu.score;
return os;
}
//读取student_info.txt,填充存储学生类对象的容器students
void student_info_parser(string file_name, vector<Student> &students)
{
fstream fstrm;
Student stu;
fstrm.open("student_info.txt",ios::in);
if(!fstrm) printf("Open Error\n");
while(fstrm>>stu.name)
{
fstrm>>stu.sex;
fstrm>>stu.number;
fstrm>>stu.score;
students.push_back(stu);//给容器类添加元素
stu.totalCount+=1;//统计总人数
stu.totalScore+=stu.score;//统计总分数
}
cout<<"the number of student is "<<stu.totalCount<<endl;
fstrm.close();
}
//此代码段为主函数文件main.cpp
#include"2Student.h"
#include"2Student.cpp"
using namespace std;
int main()
{
Student stu;
vector<Student> students;
student_info_parser("students.txt",students);
//从容器类中格式化输出学生信息
for(int i=0;i<students.size();i++)
{cout<<students[i]<<endl;}
//得到平均成绩
cout<<"The average score is "<<stu.get_average()<<endl;
return 0;
}
文本文件内容:
运行结果: