Skip to content

Checkpoint: Validate Input Lines

The Course
•
24 min study

This checkpoint is the input side of the reading log in miniature. Each line of standard input should be a duration in whole minutes, and the program must accept exactly the values from 1 to 240 and reject everything else without stopping. The supplied input is chosen with care: it holds both boundaries, the values just outside them, and a line that is not a number at all. A program that handles those five lines correctly is very likely to handle any others.

What you will use

  • A scanner loop. bufio.NewScanner(os.Stdin) and for scanner.Scan() visit each line, and scanner.Text() gives its text.
  • Trimming. strings.TrimSpace removes stray spaces before conversion, because strconv.Atoi rejects them.
  • Conversion with an error check. strconv.Atoi returns a number and an error; a non-nil error means the line was not a whole number.
  • A range check. A converted number must be at least 1 and at most 240.
  • continue. After printing Invalid, move on to the next line instead of stopping.
  • A final scanner.Err() check after the loop ends.

Plan before you type

  1. Import the five packages you need: bufio, fmt, os, strconv and strings.
  2. Create the scanner and start the loop.
  3. Trim the line and convert it, keeping both the number and the error.
  4. If the conversion failed or the number is outside the range, print Invalid and continue.
  5. Otherwise print the number.
  6. After the loop, check scanner.Err().

Before running, write the five expected output lines next to the five input lines. Then add your own test lines to the stdin box, such as 12 with spaces or an empty line, and predict them too.

One condition or two?

You can combine the checks into one condition with ||, because Go stops evaluating as soon as one part is true. If the conversion fails, the range tests never run. Separate if statements work just as well, and they let you print a different message for each problem, which the full reading log will do.

Mistakes worth checking for

  • 240 prints Invalid: the upper check uses >= instead of >.
  • 0 is printed as a valid duration: the lower check uses < 0 instead of < 1.
  • The program stops after the first bad line: a return or break was used where continue belongs.
  • later prints 0: the error from Atoi was ignored, so the failed conversion's zero value was printed.
  • The compiler reports "strings" imported and not used, or undefined: strings: the import list does not match the code.
Exercise

Your turn

Read each input line as a duration. Print whole numbers from 1 through 240 inclusive. Print Invalid for any other line, then continue. Check scanner.Err() at the end.

Your working space Go
package main

func main() {
	// Build your solution here.
}
1 0 240 241 later
Hint 1: the idea

Test conversion and both ends of the range before using the number.

Hint 2: a first step

Trim each line before passing it to strconv.Atoi.

Worked solution
Run the solution Go
package main

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

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	for scanner.Scan() {
		minutes, err := strconv.Atoi(strings.TrimSpace(scanner.Text()))
		if err != nil || minutes < 1 || minutes > 240 {
			fmt.Println("Invalid")
			continue
		}
		fmt.Println(minutes)
	}
	if err := scanner.Err(); err != nil {
		fmt.Println("Input error:", err)
	}
}
1 0 240 241 later
Text
1
Invalid
240
Invalid
Invalid

The supplied input tests both edges and the values just outside them: 1 and 240 pass, 0 and 241 fail, and later fails conversion.

Before Day 6

Check that you can do each of these without looking back:

  • Write the scanner loop from memory, including the error check after it.
  • Say what strings.Cut returns for a line with no comma.
  • Explain why converting text and checking its range are two separate steps.

Day 6 moves these checks into functions of your own. A function will return a value and an error, and a table of test cases will prove that it accepts and rejects exactly what it should.

Was this article helpful?

Your response is saved on this device.