...

/

Reading Input from the User

Reading Input from the User

This lesson explains how to receive input from the user through the keyboard.

We'll cover the following...

Apart from the packages fmt and os, we will also need to import and use the package bufio for buffered input and output.

Reading input from the keyboard #

How can we read user input from the keyboard (console)? Input is read from the keyboard or standard input, which is os.Stdin. The simplest way is to use the Scan- and Sscan-family of functions of the package fmt, as illustrated in this program:

svg viewer
package main
import "fmt"

var (
      firstName, lastName, s string
      i int
      f float32
      input = "56.12 / 5212 / Go"
      format = "%f / %d / %s"
)

func main() {
  fmt.Println("Please enter your full name: ")
  fmt.Scanln(&firstName, &lastName)
  // fmt.Scanf("%s %s", &firstName, &lastName)
  fmt.Printf("Hi %s %s!\n", firstName, lastName) // Hi Chris Naegels
  fmt.Sscanf(input, format, &f, &i, &s)
  fmt.Println("From the string we read: ", f, i, s)
}

Click the RUN button, and wait for the terminal to start. Type go run main.go and press ENTER.

The Scan functions require us to first define the variables in which the input ...