Skip to content

Commit

Permalink
Update 12.1.md
Browse files Browse the repository at this point in the history
  • Loading branch information
domainname committed Mar 16, 2015
1 parent a3a2445 commit 8a86747
Showing 1 changed file with 34 additions and 4 deletions.
38 changes: 34 additions & 4 deletions eBook/12.1.md
Original file line number Diff line number Diff line change
@@ -1,28 +1,58 @@
# 读取用户的输入

我们如何读取用户的键盘(控制台)输入呢?从键盘和标准输入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
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
// 输出结果: 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)
}
}
```

Expand Down

0 comments on commit 8a86747

Please sign in to comment.