Files
the-way-to-go_ZH_CN/eBook/12.1.md
2015-03-16 23:39:48 +08:00

941 B
Raw Blame History

读取用户的输入

我们如何读取用户的键盘控制台输入呢从键盘和标准输入os.Stdin读取输入最简单的办法是使用 fmt 包提供的 Scan 和 Sscan 开头的函数。请看以下程序:

Listing 12.1—readinput1.go:

// read input from the console:
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)
    // output: From the string we read: 56.12 5212 Go
}

链接