Reading input

Introduction

Programs become useful when they read data from the user. On this site the data comes from the Input box below the editor, and a program reads it as if it were typed on the keyboard. In Go there are two common ways to read it. fmt.Scan reads separate values, such as numbers, and is the easiest. bufio.Scanner reads whole lines, and it is the right tool when you do not know how many lines there will be. This lesson shows both, and shows how to turn text into numbers.

How it works

fmt.Scan reads values separated by spaces or new lines and stores them in variables. You give it the address of each variable with &, so Scan can change the variable:

var a, b int
fmt.Scan(&a, &b)

It does not matter whether the two numbers are on one line or on two lines. Scan chooses the conversion from the variable's type: an int variable reads a whole number, a string reads one word, a float64 reads a decimal. Scan returns two values: how many values it read, and an error. At the end of the input the error is not empty, which is how a program can find out that the input has finished.

bufio.Scanner reads text line by line. You create it once, and call Scan() in a loop; it returns true while there is a new line and false at the end:

scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
	line := scanner.Text()
	fmt.Println(line)
}

os.Stdin means the standard input, the Input box. The for loop repeats its block while the condition is true; loops are explained fully in lesson 5.

A line is only text. To work with its words, use strings.Fields, which splits a text on spaces and ignores extra spaces. To turn a word into a number, use strconv.Atoi. It returns the number and an error, which is empty (nil) when the word really is a number:

n, err := strconv.Atoi("42")

Go functions can return two values, as you see here; lesson 6 explains how to write them. One warning: use only one way of reading in a program. Do not mix fmt.Scan and bufio.Scanner, because the scanner may take more input than you expect.

Example

package main

import "fmt"

func main() {
	var n int
	fmt.Scan(&n)
	sum := 0
	for i := 0; i < n; i++ {
		var x int
		fmt.Scan(&x)
		sum += x
	}
	var name string
	var age int
	count, _ := fmt.Scan(&name, &age)
	fmt.Println("sum:", sum)
	fmt.Println("read", count, "values:", name, age)
}

Input used: 3 ⏎ 10 20 ⏎ 30 ⏎ Ada 36

package main

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

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	lines := 0
	words := 0
	last := ""
	for scanner.Scan() {
		line := scanner.Text()
		lines++
		words += len(strings.Fields(line))
		last = line
	}
	fmt.Println("lines:", lines)
	fmt.Println("words:", words)
	n, err := strconv.Atoi(strings.TrimSpace(last))
	if err == nil {
		fmt.Println("last line plus one:", n+1)
	}
}

Input used: hello go world ⏎ spaces are fine ⏎ 42

Line by line

  1. In the first program fmt.Scan(&n) reads the count, then a loop reads n numbers and adds them up.
  2. fmt.Scan(&name, &age) reads a word and a number, and returns how many values it read.
  3. In the second program bufio.NewScanner(os.Stdin) makes a scanner, and scanner.Scan() is true for each line.
  4. strings.Fields(line) splits the line into words, and len counts them.
  5. The last line is turned into a number with strconv.Atoi; strings.TrimSpace removes spaces around it first.

Expected result

With this input the first program reads three numbers and a person:

3
10 20
30
Ada 36

and prints:

sum: 60
read 2 values: Ada 36

With this input the second program reads three lines:

hello go world
  spaces   are   fine
 42

and prints:

lines: 3
words: 7
last line plus one: 43

In the real world

Almost every program reads something: a configuration, a list of orders, the lines of a log file. Command-line tools in Go read from standard input all the time, so you can connect programs together in a pipe. Competitive programmers use fmt.Scan for small inputs and a bufio Scanner for large ones, because the scanner is faster.

Common mistakes

  • Forgetting the & in fmt.Scan(&x). Without it Scan cannot change x.
  • Mixing fmt.Scan and bufio.Scanner on the same input.
  • Ignoring the error from Atoi, so a word that is not a number becomes 0 without a warning.
  • Splitting a line on a single space, which breaks with double spaces; strings.Fields is safer.

Best practices

  • Choose one way of reading and use it for the whole program.
  • Create the Scanner once, outside any loop.
  • Check the error from strconv.Atoi when the input might not be a number.

Summary

fmt.Scan(&a, &b) reads values of the type of each variable, across spaces and lines. A bufio.Scanner reads whole lines until the input ends. strings.Fields splits a line into words and strconv.Atoi converts a word to a number, returning an error when it is not one.

Quick check

1. Why does fmt.Scan need &x and not just x?
2. What does scanner.Scan() return at the end of the input?
3. Which function splits a line into words and ignores extra spaces?
4. What does strconv.Atoi("abc") return in its second value?

Key takeaways

  • fmt.Scan(&a, &b) reads values across spaces and lines; pass the address of each variable with &.
  • bufio.Scanner reads line by line; scanner.Scan() is false when the input ends.
  • strings.Fields splits a line into words and strconv.Atoi turns a word into a number.

Practice problems for this lesson

Was this lesson clear?

My notes

Write down what you want to remember from this lesson. Notes are saved on this device as you type, and appear on your dashboard.