Skip to content
AgileLogics
5 min read

Reading User Input

Prerequisites: Formatted output with fmt

The usual way to read what a user types is a bufio.Scanner wrapped around os.Stdin (standard input). It reads one line at a time.

Syntax

scanner := bufio.NewScanner(os.Stdin)
scanner.Scan()          // wait for the user to press Enter
line := scanner.Text()  // the line, without the trailing newline

Example

package main

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

func main() {
    scanner := bufio.NewScanner(os.Stdin)

    fmt.Print("What is your name? ")
    scanner.Scan()
    name := strings.TrimSpace(scanner.Text())

    fmt.Print("How old are you? ")
    scanner.Scan()
    age, err := strconv.Atoi(strings.TrimSpace(scanner.Text()))
    if err != nil {
        fmt.Println("That is not a whole number.")
        return
    }

    fmt.Printf("Hello, %s! Next year you will be %d.\n", name, age+1)
}

Expected output

If you type Ada and 36 (pressing Enter after each):

What is your name? Ada
How old are you? 36
Hello, Ada! Next year you will be 37.

The if err != nil { ... return } part means "if the conversion failed, print a message and stop" — the next lesson covers if in full.

Some details worth knowing:

  • fmt.Print (not Println) keeps the cursor on the same line as the prompt.
  • Input always arrives as a string; convert it with strconv when you need a number.
  • strings.TrimSpace removes stray spaces — and the \r that can appear on Windows when input is piped from a file.

Common mistakes

  • Using fmt.Scanln(&name) for full names: fmt.Scan-style functions split on spaces, so Ada Lovelace would only read Ada. A Scanner reads the whole line.
  • Forgetting to call scanner.Scan() before scanner.Text(), which then returns an empty string.
  • Not handling the error when converting input to a number.

Practice

Ask the user for two whole numbers (one per line) and print their sum. If either input isn't a number, print Invalid number and stop.

Show solution
package main

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

func main() {
    scanner := bufio.NewScanner(os.Stdin)

    fmt.Print("First number: ")
    scanner.Scan()
    a, err := strconv.Atoi(strings.TrimSpace(scanner.Text()))
    if err != nil {
        fmt.Println("Invalid number")
        return
    }

    fmt.Print("Second number: ")
    scanner.Scan()
    b, err := strconv.Atoi(strings.TrimSpace(scanner.Text()))
    if err != nil {
        fmt.Println("Invalid number")
        return
    }

    fmt.Println("Sum:", a+b)
}