Learn/C++/15. Final project: gradebook
Lesson 15 of 15
Sign in

C++, lesson 15

Final project: gradebook

Time to put the whole course together. You will build a small gradebook that a teacher drives with text commands: add students, record scores, ask for a report and find the top student. Nothing in it is new. The challenge is organising the pieces so the program stays easy to read and hard to break.

Design first

One class owns the data. A Gradebook class keeps the students and their scores private, and offers member functions for each operation. The rest of the program can't put the data into an inconsistent state because it can't touch it directly.

A std::map from name to a vector of scores is a good fit: names are unique, lookups are by name, and the report must be in alphabetical order, which the map gives you for free.

Errors become exceptions. The member functions check their rules and throw when a request is invalid, for example std::invalid_argument("no student " + name). The command loop in wraps each command in one block and prints plus . That keeps all the checking in one place (the class) and all the printing in another ().

One exercise to try what you just read.

Exercise 1

Gradebook

Press Ctrl Enter or Check to test your code.

main
try
Error:
e.what()
main

Optional, not magic values. top_student returns an std::optional holding the name and average (a std::pair), because a gradebook without scores has no top student, and that's a normal situation rather than an error.

Small helpers. An average function and a letter-grade function, each a few lines, keep the report code readable:

Parsing commands

Read whole lines with std::getline, then split each one with a std::istringstream. Read the command word first and decide what else to read based on it. For the score, read the token as a string and convert it with std::stoi, checking that every character was used; that turns 9x or ninety into a clean error instead of a silently wrong number.

Build in steps

  1. Get the command loop working with just add and a bare-bones report.
  2. Add score and its checks.
  3. Complete the report with averages, grades and the class average.
  4. Add top, then go through the error rules one by one.

Test after each step with a few commands of your own.

Further reading

  • cppreference: Classes
  • cppreference: std::map
  • cppreference: std::optional
  • cppreference: std::stoi
  • cppreference: std::accumulate

Read commands, one per line, until the input ends. Names are single words. Blank lines are ignored.

CommandOutput on success
add <name>Added <name>
score <name> <points>Recorded <points> for <name>
topTop: <name> (<average>), or Top: none if no student has scores
reportsee below

Errors print Error: <message> and change nothing:

  • add of an existing name: <name> already exists
  • score for an unknown name: no student <name>
  • score whose points are missing, not a whole number, or outside 0 to 100: bad score (check the name first, then the points)
  • any other command word: unknown command <word>

report prints --- report ---, then one line per student in alphabetical order: <name>: <average> <grade> (<n> scores), or <name>: no scores. Then Class average: <average of every recorded score>, or Class average: n/a if there are none.

Averages are printed with one decimal. Grades: A for 90 and above, B for 80 and above, C for 70 and above, D for 60 and above, F below that. For top, the highest average wins and ties go to the name that comes first alphabetically.

class Gradebook {
public:
    void add_student(const std::string& name);
    void add_score(const std::string& name, const std::string& points);
    std::optional<std::pair<std::string, double>> top_student() const;   // name and average
    void print_report(std::ostream& out) const;

private:
    std::map<std::string, std::vector<int>> scores_;
};
double average(const std::vector<int>& v) {
    return std::accumulate(v.begin(), v.end(), 0.0) / v.size();
}

char letter(double avg) {
    if (avg >= 90) return 'A';
    if (avg >= 80) return 'B';
    // ...
}
std::string line;
while (std::getline(std::cin, line)) {
    std::istringstream in{line};
    std::string command;
    if (!(in >> command)) {
        continue;                       // skip blank lines
    }
    try {
        // dispatch on command ...
    } catch (const std::exception& e) {
        std::cout << "Error: " << e.what() << '\n';
    }
}
Input:
add zoe
add ali
add zoe
score ali 91
score ali 84
score zoe 70
score bob 50
score zoe 101
top
report
Output:
Added zoe
Added ali
Error: zoe already exists
Recorded 91 for ali
Recorded 84 for ali
Recorded 70 for zoe
Error: no student bob
Error: bad score
Top: ali (87.5)
--- report ---
ali: 87.5 B (2 scores)
zoe: 70.0 C (1 scores)
Class average: 81.7