Skip to content

On Your Own: A Reading Planner

The Course
•
60 min study

Following a walkthrough shows that you can recognize good code. Building something new from a brief shows that you can produce it. This checkpoint asks for a whole program in a different domain, a reading list, so you cannot copy the planner line by line. You decide the records, the functions, where validation goes and what you test. There is no plan below on purpose: the brief, the sample and your own tests are all you get.

The brief

A reading planner reads one entry per line from standard input, in this format: a page count, a finished flag (0 or 1), then the title, separated by spaces. For example, 20 0 Dune is an unfinished 20-page book called Dune.

  • Accept page counts of 1 through 500 and titles of 1 through 40 characters. Any other line, including one that is not in the format at all, is rejected and counted.
  • Print each accepted entry, in input order, as Reading: Title (N pages) or Finished: Title (N pages).
  • Then print the number of accepted lines, the number of rejected lines, and the total pages of accepted entries that are not finished.
  • Keep parsing, validation and totals in functions, and only main reads input and prints.
  • Test those functions with assertions that run before the report: every boundary in the rules above, a line that is not a number, a bad flag, and empty input.

With this input:

Text
20 0 Dune
10 1 Emma
0 0 Broken
500 0 Middlemarch
501 0 Too long
later 0 Notes

the program prints exactly:

Text
Reading: Dune (20 pages)
Finished: Emma (10 pages)
Reading: Middlemarch (500 pages)
Accepted: 3
Rejected: 3
Unfinished pages: 520

Predict and run

Predict before running C++
#include <iostream>

int main() {
    int pages = 20;
    bool finished = false;
    std::cout << (finished ? 0 : pages) << "\n";
    return 0;
}
Check your prediction
Text
20

This line handles one record's contribution to unfinished pages, and nothing else. Before starting, list what the brief needs that it does not do. Then decide your function names and contracts, and write them as comments, before any code.

Practice

Exercise

Your turn

Build the reading planner from the brief. The sample input is loaded into the editor, and your edits are saved in this browser. The starter only counts lines, so you can see the input arrive.

Your working space C++
#include <iostream> #include <string> int main() { // The sample input is already loaded. Replace this loop with your planner. std::string line; int lines = 0; while (std::getline(std::cin, line)) { ++lines; } std::cout << "Read " << lines << " lines\n"; return 0; } 20 0 Dune 10 1 Emma 0 0 Broken 500 0 Middlemarch 501 0 Too long later 0 Notes
Hint 1: the idea

This is the study planner's shape in a new domain: one function turns a line into a record or reports failure without changing its output, one rule decides validity, and one function adds up a vector it only reads. Rejecting a line is a normal result, so it is counted, not printed as an error.

Hint 2: a first step

Write the record and the parsing function first, and test only it: "20 0 Dune" succeeds and fills the record, and "501 0 Too long" fails and leaves a record you filled beforehand unchanged. Leave the report for last.

Show one solution

One complete answer, with its checks in run_checks():

Run the solution C++
#include <cassert> #include <iostream> #include <sstream> #include <string> #include <vector> struct Reading { std::string title; int pages = 0; bool finished = false; }; struct Summary { int accepted = 0; int rejected = 0; int unfinished_pages = 0; }; // Pages 1..500 and a title of 1..40 characters. bool valid_reading(const Reading& entry) { return entry.pages >= 1 && entry.pages <= 500 && !entry.title.empty() && entry.title.size() <= 40; } // One line: pages, a 0/1 finished flag, then the title. // Failure leaves out unchanged. bool parse_reading(const std::string& line, Reading& out) { std::istringstream input(line); Reading candidate; int finished = 0; if (!(input >> candidate.pages >> finished) || (finished != 0 && finished != 1)) { return false; } std::getline(input >> std::ws, candidate.title); candidate.finished = finished == 1; if (!valid_reading(candidate)) { return false; } out = candidate; return true; } // Unfinished pages count only accepted, unfinished entries. int unfinished_pages(const std::vector<Reading>& entries) { int total = 0; for (const Reading& entry : entries) { if (!entry.finished) { total += entry.pages; } } return total; } // Parses every line, keeping accepted entries in order. Rejected lines are only counted. Summary summarize(const std::vector<std::string>& lines, std::vector<Reading>& accepted) { Summary summary; for (const std::string& line : lines) { Reading entry; if (parse_reading(line, entry)) { accepted.push_back(entry); ++summary.accepted; } else { ++summary.rejected; } } summary.unfinished_pages = unfinished_pages(accepted); return summary; } void run_checks() { Reading entry{"Kept", 7, true}; assert(parse_reading("20 0 Dune", entry)); assert(entry.title == "Dune" && entry.pages == 20 && !entry.finished); assert(parse_reading("1 0 A", entry) && entry.pages == 1 && entry.title == "A"); const std::string forty(40, 'a'); assert(parse_reading("20 0 " + forty, entry) && entry.title == forty); assert(parse_reading("500 1 Limit", entry) && entry.pages == 500 && entry.finished); assert(!parse_reading("501 0 Too long", entry)); assert(!parse_reading("0 0 Broken", entry)); assert(!parse_reading("20 2 Flag", entry)); assert(!parse_reading("20 0", entry)); assert(!parse_reading("x 0 Bad", entry)); assert(!parse_reading("20 0 " + forty + "a", entry)); assert(entry.title == "Limit" && entry.pages == 500); std::vector<Reading> none; const Summary empty = summarize({}, none); assert(empty.accepted == 0 && empty.rejected == 0 && empty.unfinished_pages == 0 && none.empty()); std::vector<Reading> kept; const Summary mixed = summarize({"20 0 Dune", "bad", "", "10 1 Emma"}, kept); assert(mixed.accepted == 2 && mixed.rejected == 2 && mixed.unfinished_pages == 20); assert(kept.size() == 2 && kept[1].title == "Emma"); } int main() { run_checks(); std::vector<std::string> lines; std::string line; while (std::getline(std::cin, line)) { lines.push_back(line); } std::vector<Reading> entries; const Summary summary = summarize(lines, entries); for (const Reading& entry : entries) { std::cout << (entry.finished ? "Finished: " : "Reading: ") << entry.title << " (" << entry.pages << " pages)\n"; } std::cout << "Accepted: " << summary.accepted << '\n'; std::cout << "Rejected: " << summary.rejected << '\n'; std::cout << "Unfinished pages: " << summary.unfinished_pages << '\n'; return 0; } 20 0 Dune 10 1 Emma 0 0 Broken 500 0 Middlemarch 501 0 Too long later 0 Notes

Validation lives in valid_reading, so parsing cannot accept a record the rules reject, and parse_reading only writes to out after every check has passed, which the 41-character case proves by reading the earlier Limit entry back. Each bound has a case on both sides: 1 and 500 pages pass while 0 and 501 fail, and a 1-character and a 40-character title pass while 41 characters fail. Reading lines into a vector first lets summarize be tested on empty input, which must give three zeros, as well as on a mix of good, bad and empty lines. The flag is read as an int and checked, so 20 2 Flag is rejected instead of quietly becoming true. unfinished_pages takes a const reference: it reads the plan and cannot change it, and the empty vector gives 0 through the loop's starting total with no special case. Your version can differ in names and layout. What matters is that each rule in the brief has an assertion that would fail if the rule broke.

Check your own work

Before you look at the solution, or after you finish, answer each of these honestly. Each "no" points at the lesson to revisit.

  • Does your program print the sample output exactly, character for character? (Day 1, Day 4)
  • Do 1 and 500 pages pass while 0 and 501 fail, and does each of those cases have its own assertion? (Day 3)
  • Does a failed parse leave the record unchanged, and is there an assertion that shows it? (Day 6)
  • Do your totals take the vector by const reference? (Day 5)
  • Break one rule on purpose, such as pages <= 500 to pages < 500. Does an assertion stop the run? If not, which case is missing? (Day 3)
  • Could someone tell from your function names and comments what each one promises, without reading the bodies? (Day 6)

Was this article helpful?

Your response is saved on this device.