mirror of
https://github.com/unknwon/the-way-to-go_ZH_CN.git
synced 2025-08-11 23:08:34 +08:00
Create 12.1.md
This commit is contained in:
33
eBook/12.1.md
Normal file
33
eBook/12.1.md
Normal file
@@ -0,0 +1,33 @@
|
||||
# 读取用户的输入
|
||||
|
||||
我们如何读取用户的键盘(控制台)输入呢?从键盘和标准输入(os.Stdin)读取输入,最简单的办法是使用 `fmt` 包提供的 Scan 和 Sscan 开头的函数。请看以下程序:
|
||||
|
||||
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
|
||||
}
|
||||
```
|
||||
|
||||
## 链接
|
||||
|
||||
- [目录](directory.md)
|
||||
- 上一节:[读写数据](12.0.md)
|
||||
- 下一节:[文件读写](12.2.md)
|
Reference in New Issue
Block a user