Skip to content

Checkpoint: Parse a Stream of Records

The Course
•
30 min study

This checkpoint reads real program input. You will write an iterator over standard input that yields numbered, non-blank lines, and a consumer that parses each line as it arrives. The consumer stops at the first bad line, and the iterator must notice that and stop reading. That is the same split as in the project: one piece knows how to read lines, and another knows what a line means.

What you will use

  • iter.Seq2[int, string]. The iterator yields each line number with the trimmed text, skipping blank lines.
  • bufio.Scanner over os.Stdin. The input box under the editor is already filled in. Edit it before pressing Run.
  • A limit. Refuse lines longer than 40 bytes by giving the scanner a 41-byte buffer, as in the last lesson.
  • An early stop. The consumer breaks out of the loop at the first record it cannot parse, and the iterator returns when yield reports false.

Plan before you type

  1. Write records(scanner *bufio.Scanner) iter.Seq2[int, string], which numbers every line but only yields the non-blank ones.
  2. In main, create the scanner, set the buffer to 41 bytes, and range over records(scanner).
  3. For each line, parse ITEM QUANTITY with strings.Fields and strconv.Atoi.
  4. On the first failure, print the line number and the problem, and break.
  5. After the loop, check scanner.Err() and print a summary of the units read.
Prove the iterator stops reading

Add a print inside the iterator just before each yield. After a bad line, no further lines should be printed, even though the input has more. Remove the print when you are done.

Mistakes worth checking for

  • range function continued iteration: the iterator ignores the result of yield and keeps scanning after the break.
  • Line numbers shift after a blank line: the counter is increased only for yielded lines.
  • The summary counts the bad line's units: the total is updated before the line is fully validated.
  • The scanner error is never checked: an over-long line simply ends the loop silently, as if the input had ended.
Exercise

Your turn

Read ITEM QUANTITY records from stdin with your iterator. Print each accepted record. Stop at the first line that has the wrong number of fields or a quantity that is not a positive whole number, print Line N: ... for it, and finish with the number of records and units accepted. The input contains a blank line and a bad record before the end.

The output should be:

Text
Accepted tent 3
Accepted drill 2
Line 4: "two" is not a positive whole number
Records: 2 | Units: 5
Your working space Go
package main

func main() {
	// Write records, then parse stdin until the first bad line.
}
tent 3 drill 2 lamp two hat 1
Hint 1: the idea

The iterator owns the line numbers and the blank-line rule. The loop body owns the meaning of a record and the decision to stop.

Hint 2: a first step

Write the iterator's loop as for number := 1; scanner.Scan(); number++, trim the text, continue when it is empty, and return when yield(number, text) is false.

Worked solution
Run the solution Go
package main

import (
	"bufio"
	"fmt"
	"iter"
	"os"
	"strconv"
	"strings"
)

const maxLine = 40

func records(scanner *bufio.Scanner) iter.Seq2[int, string] {
	return func(yield func(int, string) bool) {
		for number := 1; scanner.Scan(); number++ {
			text := strings.TrimSpace(scanner.Text())
			if text == "" {
				continue
			}
			if !yield(number, text) {
				return
			}
		}
	}
}

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Buffer(make([]byte, 0, maxLine+1), maxLine+1)
	count, units := 0, 0
	for number, text := range records(scanner) {
		fields := strings.Fields(text)
		if len(fields) != 2 {
			fmt.Printf("Line %d: use ITEM QUANTITY\n", number)
			break
		}
		n, err := strconv.Atoi(fields[1])
		if err != nil || n < 1 {
			fmt.Printf("Line %d: %q is not a positive whole number\n", number, fields[1])
			break
		}
		fmt.Println("Accepted", fields[0], n)
		count++
		units += n
	}
	if err := scanner.Err(); err != nil {
		fmt.Println("read input:", err)
	}
	fmt.Printf("Records: %d | Units: %d\n", count, units)
}
tent 3 drill 2 lamp two hat 1
Text
Accepted tent 3
Accepted drill 2
Line 4: "two" is not a positive whole number
Records: 2 | Units: 5

hat 1 is valid but was never read, because the break stopped the iterator before it scanned another line. Make the first line longer than 40 bytes and run again: the loop ends at once, and the scanner error is printed before the summary. The bad line is reported as line 4, counting the blank line, so the message matches what the person sees in their input.

Was this article helpful?

Your response is saved on this device.