Skip to content

On Your Own: A Reading Tracker

The Course
•
40 min study

The best test of a design is to use it again for something new. In this checkpoint you build a reading tracker from scratch: the same shape as the study planner, with its own fields and limits. Nothing is spliced in for you, so plan before you type, and test the edges once it runs.

What you will use

  • A struct that owns its text. Reading stores the title as a String, copied only after the line passes every check.
  • A parser that returns Result. parse_reading(line: &str) -> Result<Reading, &'static str> borrows the line and either builds a Reading or explains the problem.
  • split_once and trim. Split on the first comma, then trim both halves before checking them.
  • A guarded match on parse::<u32>(). Separate "not a number" from "outside 1–500".
  • A line loop with enumerate(). index + 1 gives the line number for each error message.
  • A u64 total. u64::from(pages) widens each count before adding, so the sum has room to grow.

Plan before you type

  1. Write parse_reading first and give it the four outcomes: no comma, empty title, bad number, out of range.
  2. In main, create an empty vector, and in the loop push each Ok reading and print each Err with its line number.
  3. After the loop, borrow the vector to print each reading and add up the pages.
  4. Run the supplied input, then the boundary and empty cases listed in the task.
Prove each rule rejects

Run one line for each rule and confirm its message: Notes with no comma, ,12 with no title, Notes,many, Notes,0 and Notes,501. Then run Notes,500 and confirm it is accepted. If any of these surprises you, the order of your checks or a comparison is off.

Mistakes worth checking for

  • Titles print with spaces around them: the title was stored before trimming.
  • A line with two commas, such as Rust, Vol. 2,40, is rejected as not a number: split_once splits at the first comma, so the second piece is Vol. 2,40. That is acceptable for this task, but know why it happens.
  • Every error says line 1: the line number was computed outside the loop, or enumerate() was left out.
  • mismatched types when adding to the total: a u32 was added to a u64 without u64::from.
  • The total is missing from empty input: the final println! sits inside the loop instead of after it.
Exercise

Your turn

Build a reading tracker from the supplied input loop. Each line should have a title and page count separated by a comma. Trim both parts. Require a nonempty title and 1–500 pages. Skip blank lines (including lines of only spaces) without a message, as the planner does, but still count them, so later line numbers match the input. For any other malformed line, print the line number and the reason, and carry on. After the input ends, print the valid entries in order and the total of their pages.

Use these messages, checked in this order:

ProblemExample lineMessage
no commaNotesLine N: use title,pages
empty title ,12Line N: enter a title
not a whole numberNotes,manyLine N: enter a whole number
outside 1–500Notes,0Line N: use 1–500 pages

Each valid entry prints as Title: P pages, and the last line is Total pages: T. For the supplied input, whose third line is blank, the program should print:

Text
Line 2: use 1–500 pages
Rust Notes: 24 pages
Practice Guide: 12 pages
Total pages: 36

Then run a case with exactly 500 pages and one with 501. Try an empty input and check that the only line printed is Total pages: 0.

Use a u64 total to leave room for sums larger than an individual u32 count. Convert a page count with u64::from(pages) before adding it.

Your working space Rust
use std::io::{self, BufRead};

struct Reading {
    title: String,
    pages: u32,
}

fn main() {
    // Store accepted readings in a vector.
    for (index, line) in io::stdin().lock().lines().enumerate() {
        match line {
            Ok(line) => println!("Line {}: {line}", index + 1),
            Err(_) => {
                eprintln!("Could not read line {}", index + 1);
                break;
            }
        }
    }
    // Print the accepted titles and the total pages.
}
Rust Notes,24 Skip me,0 Practice Guide,12
Hint 1: the idea

Write a parser that borrows a line and returns either an owned Reading or an error message.

Hint 2: a first step

Begin with split_once(','). In the Some arm, give the two pieces names you can trim and validate.

Worked solution
Run the solution Rust
use std::io::{self, BufRead};

struct Reading {
    title: String,
    pages: u32,
}

fn parse_reading(line: &str) -> Result<Reading, &'static str> {
    let (title, pages) = match line.split_once(',') {
        Some(pair) => pair,
        None => return Err("use title,pages"),
    };
    let title = title.trim();
    if title.is_empty() {
        return Err("enter a title");
    }
    match pages.trim().parse::<u32>() {
        Ok(pages) if pages >= 1 && pages <= 500 => {
            Ok(Reading { title: String::from(title), pages })
        }
        Ok(_) => Err("use 1–500 pages"),
        Err(_) => Err("enter a whole number"),
    }
}

fn main() {
    let mut readings = Vec::new();
    for (index, line) in io::stdin().lock().lines().enumerate() {
        match line {
            Ok(line) => {
                if line.trim().is_empty() {
                    continue;
                }
                match parse_reading(&line) {
                    Ok(reading) => readings.push(reading),
                    Err(message) => println!("Line {}: {message}", index + 1),
                }
            }
            Err(_) => {
                eprintln!("Could not read line {}", index + 1);
                break;
            }
        }
    }

    let mut total = 0_u64;
    for reading in &readings {
        println!("{}: {} pages", reading.title, reading.pages);
        total += u64::from(reading.pages);
    }
    println!("Total pages: {total}");
}
Rust Notes,24 Skip me,0 Practice Guide,12
Text
Line 2: use 1–500 pages
Rust Notes: 24 pages
Practice Guide: 12 pages
Total pages: 36

Each valid line becomes a Reading that owns its title. The output loop borrows each Reading and adds its page count. The error path prints a message and leaves the vector alone. The early return Err(...) inside the first match keeps the rest of the function flat: once the line has been split, the code below can assume both halves exist. With no valid entries the loop over &readings simply does not run, and the report shows Total pages: 0. continue skips the rest of one loop pass and moves on to the next line, where break would end the loop; the planner gets the same effect with an if around its work, and either is fine.

Check your own work

Before you open the solution, or after you finish without it, go through this list. Each item is a run you can do in the stdin box.

  • The supplied input prints exactly the four lines above, with line 3 skipped silently.
  • Notes,500 is accepted and Notes,501 gives use 1–500 pages.
  • Each row of the message table produces its own message, with the right line number.
  • Spaced Title , 8 prints as Spaced Title: 8 pages, with no extra spaces.
  • Input with only blank or invalid lines ends with Total pages: 0.
  • parse_reading borrows a &str and makes the String only after every check has passed.

If every box is ticked, you have used the planner's design on a problem of your own. If one fails, the Mistakes worth checking for list above names the usual cause.

Was this article helpful?

Your response is saved on this device.