Line by Line with bufio.Scanner
io.ReadAll reads the whole input at once, and that's enough for most puzzles. Another way that's just as common is reading one line at a time with bufio.Scanner:
scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
line := scanner.Text() // one line, without the "\n"
fmt.Println(len(line))
}
if err := scanner.Err(); err != nil {
fmt.Println("read error:", err)
}
Scan() returns true as long as there's another line. After the loop, Err() tells you whether it stopped because the input ran out (nil) or because of an error.
Take an io.Reader, not os.Stdin
Look at the function signature in this task: readNumbers(r io.Reader). The function doesn't care where the text comes from. main hands it os.Stdin, and the tests hand it strings.NewReader("21\n23\n"). Separating reading the input from the logic like this keeps your code easy to test, and it's how the hidden tests in this course call your functions.
Cleaning a line and turning it into a number
Real input is rarely tidy. There are spaces at the end of lines, blank lines, or a trailing \r from a file made on Windows. strings.TrimSpace removes all of them at once:
line := strings.TrimSpace(scanner.Text())
if line == "" {
continue // skip blank lines
}
n, err := strconv.Atoi(line)
if err != nil {
return nil, fmt.Errorf("line %d: %w", lineNo, err)
}
strconv.Atoi rejects anything that isn't a whole number, including "1.5" and "3 4". Naming the line number in the error helps a lot when your puzzle input turns out to be different from what you expected.
Task
A weather station logs the temperature every hour, one whole number per line. Sometimes there's a blank line where the sensor was off.
- Complete
readNumbers(r io.Reader) ([]int, error). Clean every line withstrings.TrimSpace, skip blank lines, and convert the rest withstrconv.Atoi. If any line isn't a whole number, return an error. - Complete
biggestRise(temps []int) int: the largest increase from one reading to the next (temps[i] - temps[i-1]). If the temperature never goes up, or there are fewer than two readings, return0.
Press Run to try it with the lesson's input, then Submit.