Skip to content
Tutorials Center
My learning

Topics

Lesson 6 of 147 ยท Getting Started

Reading Input

Learn to read input in Go with bufio.Scanner, bufio.Reader, fmt.Scan and Sscanf, convert text to numbers safely with strconv, handle EOF, and use the Input box.

Programs become interesting when they react to data: a name typed by a user, numbers piped from another program, a file full of lines. In Go, all of that arrives through the same idea: standard input (os.Stdin), a stream of bytes you read piece by piece. There are three common ways to read it, each with a different strength.

This lesson shows bufio.Scanner (the everyday choice for lines and words), bufio.Reader (when you need more control), and the fmt.Scan family (convenient for formatted values). You will also learn how to turn text into numbers without crashing, how to recognize the end of the input, and how to use the Input box that appears under the editors on this site.

Whenever a program reads input, the editor shows an Input box. Type the lines your program should read there before pressing Run. In the examples below the box is already filled in for you. On your own computer you would type into the terminal, or pipe a file in with ./program < data.txt.

Reading lines with bufio.Scanner

bufio.NewScanner wraps a reader and hands you one token at a time. By default a token is a line, with the line ending removed. The loop for scanner.Scan() { ... } runs until the input is used up.

Go Reading lines

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Points to notice:

  • scanner.Scan() returns true while it has a token. It returns false at the end of the input or on an error, so check scanner.Err() after the loop. A normal end of input is not an error, and Err returns nil then.
  • scanner.Text() gives the current line as a string. The empty third line is a real token with length zero. The last line has no newline at the end, and it is still returned.
  • A Windows-style \r\n ending is trimmed too.

Reading words instead of lines

Tell the scanner what a token is with Split. The ready-made split functions are bufio.ScanLines (the default), bufio.ScanWords, bufio.ScanRunes and bufio.ScanBytes.

Go Counting words

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Words are separated by any amount of whitespace, including newlines, so the extra spaces in the input make no difference.

The line length limit

A Scanner refuses tokens longer than 64 KB by default, to protect your memory. When that happens Scan returns false and Err() reports bufio.Scanner: token too long. You can raise the limit with scanner.Buffer, which takes an initial buffer and a maximum size:

Go Lines longer than 64 KB

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

With the default limit, the first scanner stops before delivering any line (nothing is printed by the loop) and reports bufio.Scanner: token too long. The second one handles both lines. Notice that the program reads from strings.NewReader, not from the keyboard. Scanner works with any io.Reader: a file, a network connection or an in-memory string. That makes code easy to test, because you can feed it text instead of a terminal.

Reading with bufio.Reader

A bufio.Reader gives you lower-level control. ReadString(delim) returns everything up to and including a delimiter byte, such as '\n'. It has no length limit, but it returns the delimiter and it signals the end of the input with io.EOF together with the last, unterminated piece of text. The pattern is therefore a little more subtle than with Scanner:

Go ReadString and io.EOF

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The last line arrives together with io.EOF, which is why the code processes line before checking the error. Forgetting this is a classic bug: the final line without a newline is silently dropped. When you do not need that control, use a Scanner.

Other useful methods are ReadRune (one Unicode character), ReadByte, Peek and ReadLine (low level, rarely needed).

fmt.Scan, Scanln and Sscanf

The fmt package can parse input directly into variables, using pointers (so you pass &x). The three families:

  • fmt.Scan(&a, &b) reads space-separated values, treating newlines as spaces.
  • fmt.Scanln(&a, &b) stops at the end of the line and needs the right number of values on it.
  • fmt.Scanf(format, ...) and fmt.Sscanf(text, format, ...) read according to a format string. Sscanf reads from a string you already have, which is handy for parsing a single line.

All of them return the number of items parsed and an error.

Go fmt.Scan for formatted values

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

fmt.Scan is perfect for competitive-programming style input with a few numbers. For anything else, prefer bufio.Scanner plus explicit parsing, for these reasons:

  • Scan into a number stops with an error at the first bad character, and the unread rest of the line stays in the input, which can confuse later reads.
  • Reading millions of values with fmt.Scan directly from os.Stdin is slow. Wrap os.Stdin in a bufio.Reader (fmt.Fscan(reader, &x)) when speed matters.
  • You decide how errors are reported.

Sscanf is a quick way to split a line with a known shape:

Go Sscanf on a line

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The second call prints 1 expected integer: one item was parsed (name), and the integer could not be read from high.

Converting text to numbers safely

Whatever you read with a Scanner or a Reader is text. The strconv package turns it into numbers and tells you when that is impossible:

  • strconv.Atoi(s) parses a decimal int.
  • strconv.ParseInt(s, base, bits), ParseUint, ParseFloat(s, 64) and ParseBool handle other types and bases.
  • Every function returns (value, error). Always check the error. Never use the value when err != nil.
Go Parsing numbers and handling bad input

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The error messages are informative: invalid syntax for abc and 3.5 and the empty line, and value out of range for the number that does not fit in an int. When you need to react differently, use errors.Is(err, strconv.ErrSyntax) or strconv.ErrRange (Wrapping Errors explains errors.Is).

Prompts and when stdin is not a terminal

Interactive programs print a prompt and then read. Print the prompt with fmt.Print (no newline) so the cursor stays on the same line. Be aware that your program does not know whether a person or a file is behind os.Stdin: the code is exactly the same, and when the input ends, Scan returns false. That is why a program that loops "until the user types quit" must also stop at end of input.

Go
scanner := bufio.NewScanner(os.Stdin)
for {
	fmt.Print("> ")
	if !scanner.Scan() {
		break // end of input (Ctrl+D on Linux/macOS, Ctrl+Z then Enter on Windows)
	}
	if scanner.Text() == "quit" {
		break
	}
	// handle the command...
}

A related trap: if you read the first line with fmt.Scan and the next lines with a Scanner on the same os.Stdin, the scanner has its own buffer and may consume input the first call would have read. Pick one approach per program, or share one bufio.Reader for everything. The next lessons build on this; see also os, io and bufio for the full picture of readers and writers.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does scanner.Scan() return at the end of the input?

    Scan returns false at the end of input. A normal end is not reported as an error, so Err() returns nil.
  2. 2. Why must you process the returned line before checking err == io.EOF when using ReadString?

    ReadString returns the text it did read along with io.EOF when the input does not end with the delimiter.
  3. 3. What is the default maximum token size of a bufio.Scanner, and how do you change it?

    Tokens above 64 KB make Scan fail with 'token too long'. scanner.Buffer sets a bigger initial buffer and maximum.
  4. 4. What does strconv.Atoi("3.5") return?

    Atoi parses integers only. A decimal point is invalid syntax, so it returns 0 and an error.
  5. 5. Which function is the best fit for parsing the shape 'x=%d y=%d' from a string you already have?

    Sscanf parses a string according to a format. Scanln reads from standard input.

Summary

  • Standard input is os.Stdin; wrap it in bufio.NewScanner to read lines (default) or words (bufio.ScanWords).
  • Call scanner.Err() after the loop. Lines over 64 KB need scanner.Buffer.
  • bufio.Reader.ReadString('\n') has no length limit but returns the last unterminated line together with io.EOF.
  • fmt.Scan, Scanln, Scanf and Sscanf parse into variables through pointers. Handy, but slower and fussier.
  • Convert text with strconv (Atoi, ParseInt, ParseFloat, ParseBool) and always check the error.
  • Preset the Input box for any example that reads stdin, and handle end of input in loops.

Next: The go Command and Basic Tooling shows the everyday tools that keep your code formatted and correct.