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(notPrintln) keeps the cursor on the same line as the prompt.- Input always arrives as a
string; convert it withstrconvwhen you need a number. strings.TrimSpaceremoves stray spaces — and the\rthat 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, soAda Lovelacewould only readAda. AScannerreads the whole line. - Forgetting to call
scanner.Scan()beforescanner.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)
}