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.
Readingstores the title as aString, 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 aReadingor explains the problem. split_onceandtrim. Split on the first comma, then trim both halves before checking them.- A guarded
matchonparse::<u32>(). Separate "not a number" from "outside 1–500". - A line loop with
enumerate().index + 1gives the line number for each error message. - A
u64total.u64::from(pages)widens each count before adding, so the sum has room to grow.
Plan before you type
- Write
parse_readingfirst and give it the four outcomes: no comma, empty title, bad number, out of range. - In
main, create an empty vector, and in the loop push eachOkreading and print eachErrwith its line number. - After the loop, borrow the vector to print each reading and add up the pages.
- 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_oncesplits at the first comma, so the second piece isVol. 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 typeswhen adding to the total: au32was added to au64withoutu64::from.- The total is missing from empty input: the final
println!sits inside the loop instead of after it.
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:
| Problem | Example line | Message |
|---|---|---|
| no comma | Notes | Line N: use title,pages |
| empty title | ,12 | Line N: enter a title |
| not a whole number | Notes,many | Line N: enter a whole number |
| outside 1–500 | Notes,0 | Line 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:
Line 2: use 1–500 pages
Rust Notes: 24 pages
Practice Guide: 12 pages
Total pages: 36Then 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.
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.
}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
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}");
}Line 2: use 1–500 pages
Rust Notes: 24 pages
Practice Guide: 12 pages
Total pages: 36Each 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,500is accepted andNotes,501givesuse 1–500 pages.- Each row of the message table produces its own message, with the right line number.
Spaced Title , 8prints asSpaced Title: 8 pages, with no extra spaces.- Input with only blank or invalid lines ends with
Total pages: 0. parse_readingborrows a&strand makes theStringonly 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.
Completion is saved in this browser only. It does not measure mastery.