diff --git a/eBook/12.1.md b/eBook/12.1.md index 57fe45a8b..6939d74c4 100644 --- a/eBook/12.1.md +++ b/eBook/12.1.md @@ -1,13 +1,14 @@ # 读取用户的输入 -我们如何读取用户的键盘(控制台)输入呢?从键盘和标准输入(os.Stdin)读取输入,最简单的办法是使用 `fmt` 包提供的 Scan 和 Sscan 开头的函数。请看以下程序: +我们如何读取用户的键盘(控制台)输入呢?从键盘和标准输入 `os.Stdin` 读取输入,最简单的办法是使用 `fmt` 包提供的 Scan 和 Sscan 开头的函数。请看以下程序: -Listing 12.1—readinput1.go: +**Listing 12.1—readinput1.go:** ```go -// read input from the console: +// 从控制台读取输入: package main import "fmt" + var ( firstName, lastName, s string i int @@ -15,6 +16,7 @@ var ( input = "56.12 / 5212 / Go" format = "%f / %d / %s" ) + func main() { fmt.Println("Please enter your full name: ") fmt.Scanln(&firstName, &lastName) @@ -22,7 +24,35 @@ func main() { 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 + // 输出结果: From the string we read: 56.12 5212 Go +} +``` + +`Scanln` 扫描来自标准输入的文本,将空格分隔的值依次存放到后续的参数内,直到碰到换行。`Scanf` 与其类似,除了 `Scanf` 的第一个参数用作格式字符串,用来决定如何读取。`Sscan` 和以 `Sscan` 开头的函数则是从字符串读取,除此之外,与 `Scanf` 相同。如果这些函数读取到的结果与您预想的不同,您可以检查成功读入数据的个数和返回的错误。 + +您也可以使用 `bufio` 包提供的缓冲读取(buffered reader)来读取数据,正如以下例子所示: + +**Listing 12.2—readinput2.go:** + +```go +package main +import ( + "fmt" + "bufio" + "os" +) + +var inputReader *bufio.Reader +var input string +var err error + +func main() { + inputReader = bufio.NewReader(os.Stdin) + fmt.Println("Please enter some input: ") + input, err = inputReader.ReadString('\n') + if err == nil { + fmt.Printf("The input was: %s\n", input) + } } ```