Skip to content
Tutorials Center
My learning

Topics

Lesson 153 of 171 Β· Projects

Project: Grade Book

Build a C++ grade book in four stages. Parse names and scores from input, reject bad lines with std::expected, compute statistics and print a neat report.

You've learned vectors, strings, functions and algorithms one at a time. This project puts them to work together on a job every teacher knows: turning a list of names and scores into a class report. The program reads the class from the Input box, checks every line, works out averages, letter grades and class statistics, and prints a table you could pin to a notice board.

You'll build it in four stages. Each stage is a complete program that contains everything written so far, so you can run any of them on its own, edit the Input box and watch the result change. Every run starts fresh and takes a few seconds to compile. Along the way you'll make the decisions real programs need: how to split a line into a name and numbers, what to do with a line that's wrong, how to round without contradicting yourself, and how to line up columns whose width you don't know in advance.

The project practices std::vector, structs, reading input, std::string_view, string-to-number conversion, std::expected, sorting and searching algorithms, lambdas and std::format.

What we're building

The finished program reads lines like these:

TEXT
# Period 3 - Algebra II
Amara Okafor 91 84 77 95
Chen Wei 95 98 91 99
Gus Lindqvist 70 eighty 75 60

and prints a report like this (shortened):

TEXT
Grade book: 8 students, 4 scores each

  #  Name          Scores                  Avg  Grade
  1  Chen Wei         95   98   91   99   95.8  A
  2  Farah Haddad     92   88   90 89.9   90.0  A
  ...
Skipped 3 lines:
  line 8: 'eighty' is not a number

Here are the rules we'll support. Each line holds one student: a name of one or more words, followed by scores from 0 to 100. Blank lines and lines starting with # are ignored, so teachers can add notes. Every student must have the same number of scores as the first one, because a grade book has fixed columns. Any line that breaks a rule is skipped and reported at the end, and the rest of the class is still graded. A single typo should never cost you the whole report.

Stage 1: read, store, average

Start with the simplest version that does something useful. A Student is a name plus a list of scores, so it becomes a struct with a std::string and a std::vector<double>. The program reads the input one line at a time with std::getline, then pulls the words out of each line with a std::istringstream: the first word is the name, and every number after it is a score.

C++ Stage 1: a first grade book

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

A few choices are worth calling out:

  • Reading whole lines first. std::getline keeps each student's data together. If you read the whole input with >> instead, the program can't tell where one student ends and the next begins. Parsing a line with a string stream is the classic pattern from String Streams.
  • double scores. Teachers give half points, so int would be the wrong type.
  • std::move(student). The local student isn't needed after it's added to the vector, so moving it hands over its string and vector buffers instead of copying them (see Move Semantics).
  • const Student& in the loop. Iterating by value would copy every name and every score vector just to print them.

Run it, though, and the output shows why this is only stage 1. The input deliberately contains two problems, and both slip through:

TEXT
Amara: 86.8
Ben: 69.8
: -nan
Gus: 70.0
Chen: 95.8

The blank line became a student with no name and no scores, and 0.0 / 0 produced NaN (printed as -nan). Worse, Gus got 70.0. When >> hit the word eighty it failed, the loop stopped, and the program quietly averaged the one score it had read. A wrong number that looks plausible is the worst kind of bug, because nobody notices it. Stage 2 fixes this by refusing to guess.

Stage 2: parse carefully and report problems

Careful parsing needs answers to three questions. Where does the name end? What counts as a valid score? And what does the program do when a line is wrong?

Where the name ends. Real names have several words ("Chen Wei", "Diego Ramos"), so "the first word is the name" doesn't work. Our rule: the scores start at the first word that begins like a number, meaning a digit, a minus sign, a plus sign or a decimal point. Everything before it is the name. You might think "a word that converts to a number" would be simpler, but try it with a student called Nan Zhou. std::from_chars, like strtod, accepts nan and inf (in any letter case), so "Nan" would parse as a perfectly valid floating-point number and the student would lose her first name. Checking the first character avoids that trap, and it also lets "Gus 70 eighty" be reported as a bad score instead of being read as part of a long name.

What a valid score is. Each score word must convert completely to a number between 0 and 100. std::from_chars (see Converting Between Strings and Numbers) is ideal: it never throws, never depends on the locale, and tells you exactly where it stopped, so you can reject 12abc because it stopped early. The range check is written as !(value >= 0.0 && value <= 100.0) rather than value < 0.0 || value > 100.0. The two look equivalent, but every comparison with NaN is false, so only the first form rejects NaN. It's a cheap habit that closes a whole class of bugs.

What happens on error. A parsing function can either return a Student or explain why it couldn't. That's exactly what C++23's std::expected<T, E> models: it holds either a value of type T or an error of type E. Here the error is a std::string message. The caller checks it with if (!parsed), reads the message with parsed.error(), and gets the student with *parsed. Compared with exceptions, this keeps the "bad line" path visible right where lines are read, which suits input that is expected to be messy sometimes (see Error Handling Without Exceptions).

Problems are collected in a std::vector<std::string> and printed after everything else. Printing them as they happen would scatter warnings through the output, and a teacher wants the report first and the to-do list second.

C++ Stage 2: names, validation and error reports

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The output now contains only the four valid students, and the skipped lines explain themselves:

TEXT
Skipped 4 lines:
  line 7: 'eighty' is not a number
  line 8: Ivo Petrov has 2 scores, expected 4
  line 9: score 101 is outside 0-100
  line 10: the line has no name

Notice the line numbers count every input line, including the comment and the blank line. That's on purpose: the teacher will look for line 7 in their own file, where blank lines count too.

Some details in the code:

  • split_words returns std::string_views that point into line. No word is copied. That's safe because the views are only used while line is alive, inside one loop iteration. Storing them in a Student would create dangling views as soon as the next getline overwrites line (see the pitfalls in std::string_view). That's why Student::name is a real std::string.
  • std::views::split(' ') produces empty pieces for repeated spaces, so split_words skips them. Tabs aren't handled; that's one of the extension ideas at the end.
  • Joining the name uses C++23's std::views::join_with(' ') and std::ranges::to<std::string>(): take the words before the first score, glue them with spaces, and collect the characters into a string. A loop with += works too; the pipeline just says it in one statement (see Ranges and Views).
  • std::println can print a whole std::vector<double>, which is handy while developing. The final report formats the scores itself.

Stage 3: averages, letters and class statistics

With trustworthy data, the math is short. Each student gets an average, and the class gets five numbers: mean, median, standard deviation, lowest and highest average.

The average now lives in the Student struct, computed once after parsing. Sorting, ranking and grading all need it, and recomputing it everywhere would be wasteful and easy to get inconsistent.

That brings up rounding, the subtle part of any grading program. Farah's scores are 92, 88, 90 and 89.9, so her exact average is 89.975. Printed with one decimal, that's 90.0. If the letter grade is computed from the unrounded value, she gets a B next to a printed average of 90.0, the A boundary. Expect an angry email. The fix is a design rule: round once, at the point where the number becomes official, and use the rounded value everywhere after that. round_to_tenth does exactly that, and the letter grade is computed from its result.

The statistics use standard algorithms instead of hand-written loops:

  • std::accumulate adds up a range. Its starting value decides the type of the running total, so it must be 0.0, not 0. With 0, every addition is truncated to int and the result is silently wrong. It's one of the most common algorithm bugs in C++ (see Numeric Algorithms).
  • The median is the middle value of the sorted averages, or the mean of the two middle values when the count is even. We sort a copy, because the students' order still matters for the report.
  • std::ranges::minmax finds the smallest and largest values in one pass and returns both.
  • The standard deviation measures spread: the square root of the average squared distance from the mean. This version divides by n (the population formula), which is right for a whole class rather than a sample.
C++ Stage 3: statistics and letter grades

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Farah now shows 90.0 A, as she should. Try removing the call to round_to_tenth in grade and run it again: her printed average stays 90.0, but her letter drops to B.

Two more things changed in main. Each student is graded right after a successful parse, so a Student in the vector is always complete. And the program now checks for an empty class before computing statistics. With no students, the mean is 0.0 / 0 (NaN again), and averages[middle - 1] would read before the start of an empty vector, which is undefined behavior (see Undefined Behavior and Memory Safety). Returning a nonzero exit code also tells scripts that called the program that something went wrong.

std::views::transform(&Student::average) works because a pointer to a data member is callable: given a Student, it returns that student's average. It's a compact way to say "the averages of all students".

Stage 4: the class report

The last stage is presentation. The report should rank students from best to worst, show every score in aligned columns, summarize the class, draw a small chart of the grade distribution, and list anything that was skipped.

Ranking. std::ranges::sort takes a comparison. Sorting only by average leaves the order of tied students unspecified, which means two runs of a future version might print them differently. A tie-breaker by name makes the order deterministic. The lambda returns a.average > b.average (descending) when the averages differ, and a.name < b.name (alphabetical) when they're equal.

Column widths. Names have different lengths, and we don't know the longest one until the data is read. std::format supports dynamic widths: in {:<{}}, the inner {} takes the width from the next argument. The program finds the longest name with std::ranges::max and a projection, then uses that width for the header and every row. For the scores, each one is formatted with {:>5} into a string first. The plain {} format prints a double in its shortest exact form, so 95 stays 95 and 89.9 stays 89.9, without a trailing .0 on every whole number.

Computing before printing. All the numbers (stats, counts, widths) are computed first, and the printing code only formats them. Mixing computation into print statements makes both harder to change. If you later want an HTML or CSV report, you write a second printing function and reuse everything else.

C++ Stage 4: the complete grade book

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

That's the finished program. Let's look at the decisions in the report code more closely.

print_report takes the vector by value

print_report(std::vector<Student> students, ...) receives its own copy, because it sorts the students and the caller shouldn't be surprised by a reordered vector. main doesn't need the students afterwards, so it passes std::move(students), and the "copy" costs nothing: the vector's buffer simply changes owner. Taking a parameter by value and moving into it is the idiom for "I need my own copy, and callers who don't need theirs can give it away" (see Parameters).

Projections do the busy work

Several algorithms take a projection, a function applied to each element before it's compared or counted:

  • std::ranges::max(students, {}, [](const Student& s) { return s.name.size(); }) returns the student with the longest name. The {} means "use the default comparison, std::ranges::less".
  • std::ranges::count(students, letter, &Student::grade) counts students whose grade equals letter, without writing a lambda at all.

The header row is wrapped in std::max<std::size_t>(4, ...) so the "Name" column is never narrower than the word "Name" itself.

A lazy view for the "needs help" list

needs_help is a view: filtering and transforming happen only when it's iterated. Joining the names with ", " uses join_with again, this time with a std::string_view separator. Note the explicit std::string_view{", "}: with a plain string literal, join_with(", ") doesn't even compile, because the adaptor stores its argument by value, the literal decays to a const char*, and a pointer isn't a range.

Guarding the edges

print_report calls students.front() and std::ranges::max, both of which are undefined on an empty vector. That's safe only because main returns early when there are no students. It's worth a comment, or better, an assertion (assert(!students.empty());, see Assertions and Debugging), so the next person who calls print_report from somewhere else learns the rule immediately.

Ideas to extend it

Each idea practices a lesson from the course. Try them in the last TryIt.

  • Weighted scores. Let the first non-comment line be a header such as weights 15 15 30 40, and compute weighted averages. Validate that the weights add up to 100.
  • Drop the lowest score. Add an option that ignores each student's worst score. std::ranges::min_element finds it; think about whether to erase it or skip it in the sum.
  • Tabs and commas. Accept tabs as separators, or support CSV input like Amara Okafor,91,84,77,95 (see String Methods).
  • Per-assignment statistics. Print the average of each column under the table, so the teacher can see which test was hardest.
  • Unicode names. Add a student called ZoΓ«-Marguerite LefΓ¨vre (the longest name in the class). std::format pads strings by their estimated display width, but name.size() counts bytes, and "Γ«" and "Γ¨" take two bytes each in UTF-8, so the Name column comes out two spaces wider than it needs to be. Write a display_width function that counts only bytes that don't start with the bits 10 (UTF-8 continuation bytes, (c & 0xC0) != 0x80) and use it for name_width.
  • Write a file. Save the report to report.txt with std::ofstream, then read it back and print it (see Reading and Writing Text Files).

Check your understanding

Quick check Β· 5 questions

of 5 answered You scored / 5 Β· perfect!

  1. 1. In stage 1, why did Gus get an average of 70.0 from the line "Gus 70 eighty 75 60"?

    Once extraction fails, the stream is in a fail state and every later >> fails too. The loop ends quietly after one score, which is why stage 2 validates every word explicitly.
  2. 2. Why does stage 2 decide where the scores start by checking the first character of each word, instead of trying to convert each word to a number?

    Floating-point parsing accepts nan and inf in any letter case. A student named Nan Zhou would lose her first name. from_chars never throws; it reports errors through its result.
  3. 3. What is the result of std::accumulate(v.begin(), v.end(), 0) when v is a std::vector<double> holding 0.5, 0.5 and 0.5?

    The initial value 0 is an int, so the running total is an int. Each step computes int + double and converts back to int, truncating 0.5 to 0 every time. Use 0.0 as the initial value.
  4. 4. A student's exact average is 89.975. The report prints averages with {:.1f}. Why does the grade book round the average before choosing the letter?

    Without rounding first, the student would be printed with 90.0 but graded B. Rounding once, where the number becomes official, keeps every later use consistent.
  5. 5. Why does print_report take std::vector<Student> by value while main passes std::move(students)?

    Taking by value gives the function its own vector to reorder. Because main doesn't need the students afterwards, std::move transfers the storage instead of copying every name and score.

Summary

  • Read input line by line with std::getline, then split each line. Real data needs explicit rules for where each field starts and ends.
  • Never let a parser guess. Validate every field completely, and return std::expected<T, std::string> so a bad line produces a clear message instead of a plausible wrong number.
  • std::from_chars is strict and fast but accepts nan and inf; write range checks as !(x >= lo && x <= hi) so NaN is rejected too.
  • Round once, where a number becomes official, and use the rounded value everywhere after that.
  • std::accumulate needs 0.0 as its initial value for doubles. Guard empty inputs before computing means, medians or calling front().
  • Compute first, print second. Dynamic widths ({:<{}}), projections and views keep the report code short and readable.

Next: Project: Bank Account System, where you'll model accounts with classes and inheritance, enforce rules with exceptions and own polymorphic objects with std::unique_ptr.