C++, lesson 15
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.
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.
maintryError: e.what()mainOptional, 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:
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.
add and a bare-bones report.score and its checks.top, then go through the error rules one by one.Test after each step with a few commands of your own.
Read commands, one per line, until the input ends. Names are single words. Blank lines are ignored.
| Command | Output on success |
|---|---|
add <name> | Added <name> |
score <name> <points> | Recorded <points> for <name> |
top | Top: <name> (<average>), or Top: none if no student has scores |
report | see below |
Errors print Error: <message> and change nothing:
add of an existing name: <name> already existsscore 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)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