[OOP]hw002 Student2

来源:互联网 发布:威斯布鲁克数据 编辑:程序博客网 时间:2024/05/22 03:38

Write a CLI program that reads scores and name of students, and prints out a summary sheet.

The user can input as many students as possible. One students can have as many courses as possible.

One course consists the name of the course and the marks the student got.


没有指定每个学生的课程数,那么使用可变数组(容器verctor)来存放课程名和课程分数


// name: student.h// author: Amrzs// date: 2014/03/13#ifndef STUDENT_H#define STUDENT_H#include <string>#include <vector>using namespace std;class Student{private:    string name;    struct Course{        string name;        int score;    };    vector<Course> courses;public:    Student(string name);    ~Student();        int getSumScore();        void setCourse(string name, int score);    void printSummary();};#endif //STUDENT_H


// name: student.cpp// author: Amrzs// date: 2014/03/13#include <iostream>#include <string>#include "student.h"using namespace std;Student::Student(string name):    name(name){}Student::~Student(){}int Student::getSumScore(){        int sum = 0, courseNum = courses.size();    for(int i = 0; i < courseNum; i++)        sum += courses[i].score;        return sum;}void Student::setCourse(string name, int score){    Course course;    course.name = name;    course.score = score;    courses.push_back(course);        }void Student::printSummary(){    cout << "Name: " << name << '\t' << endl;    cout << "Courses: ";    for(int i = 0; i < courses.size(); i++)            cout << courses[i].name << " " << courses[i].score << '\t';    cout << "Sum: " << getSumScore() << '\t' << endl;}


// name: main.cpp// author: Amrzs// date: 2014/03/13#include <iostream>#include <string>#include <vector>#include "student.h"using namespace std;int main(){    vector<Student*> stuVec;    Student *pStu = NULL;    string name;    int score;    while(true){        cout << "Please input a student name, "             << "if you want to quit, input quit" << endl;                cin >> name;        if("quit" == name)            break;        pStu = new Student(name);                cout << "Please input courses' name and score, "            << "if end then input 0 0" << endl;        cin >> name >> score;        while(name != "0"){            pStu->setCourse(name, score);            cin >> name >> score;        }        stuVec.push_back(pStu);    }    for(int i = 0; i < stuVec.size(); i++){        stuVec[i]->printSummary();        delete stuVec[i];    }        return 0;}

makefile:

CPP = g++OFLAG = -oTARGET = a.out OBJS = main.o student.o$(TARGET): $(OBJS)$(CPP) $(OFLAG) $(TARGET) $(OBJS)main.o: main.cpp student.ostudent.o: student.cpp.PHONY: cleanclean:-rm $(TARGET) $(OBJS)

执行过程:

$ make

$ ./a.out < testData.txt

....

$make clean


大功告成,不过有几点不足:

1.在机房的时候忘了makefile怎么写,回来的时候看了书和陈皓的跟我学Makefile,目前这个makefile也只能凑合

2.main.cpp中新增学生应添加一个函数,增加可读性,在main()中写太多东西是不好的

3.使用了一个容器,但总觉得不是很规范

4.代码速度还是有点慢,得加油



0 0
原创粉丝点击