mirror of
https://github.com/unknwon/the-way-to-go_ZH_CN.git
synced 2025-08-12 00:43:26 +08:00
12.0-12.1
This commit is contained in:
@@ -71,6 +71,7 @@ func main() {
|
||||
屏幕是标准输出 `os.Stdout`;`os.Stderr` 用于显示错误信息,大多数情况下等同于 `os.Stdout`。
|
||||
|
||||
一般情况下,我们会省略变量声明,而使用 `:=`,例如:
|
||||
|
||||
```go
|
||||
inputReader := bufio.NewReader(os.Stdin)
|
||||
input, err := inputReader.ReadString('\n')
|
||||
@@ -81,6 +82,7 @@ input, err := inputReader.ReadString('\n')
|
||||
第二个例子从键盘读取输入,使用了 `switch` 语句:
|
||||
|
||||
示例 12.3 [switch_input.go](examples/chapter_12/switch_input.go):
|
||||
|
||||
```go
|
||||
package main
|
||||
import (
|
||||
@@ -93,12 +95,12 @@ func main() {
|
||||
inputReader := bufio.NewReader(os.Stdin)
|
||||
fmt.Println("Please enter your name:")
|
||||
input, err := inputReader.ReadString('\n')
|
||||
|
||||
|
||||
if err != nil {
|
||||
fmt.Println("There were errors reading, exiting program.")
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
fmt.Printf("Your name is %s", input)
|
||||
// For Unix: test with delimiter "\n", for Windows: test with "\r\n"
|
||||
switch input {
|
||||
@@ -107,7 +109,7 @@ func main() {
|
||||
case "Ivo\r\n": fmt.Println("Welcome Ivo!")
|
||||
default: fmt.Printf("You are not welcome here! Goodbye!")
|
||||
}
|
||||
|
||||
|
||||
// version 2:
|
||||
switch input {
|
||||
case "Philip\r\n": fallthrough
|
||||
@@ -115,7 +117,7 @@ func main() {
|
||||
case "Chris\r\n": fmt.Printf("Welcome %s\n", input)
|
||||
default: fmt.Printf("You are not welcome here! Goodbye!\n")
|
||||
}
|
||||
|
||||
|
||||
// version 3:
|
||||
switch input {
|
||||
case "Philip\r\n", "Ivo\r\n": fmt.Printf("Welcome %s\n", input)
|
||||
@@ -137,11 +139,10 @@ iii) 输入的行数
|
||||
|
||||
**练习 12.2:** [calculator.go](exercises/chapter_12/calculator.go)
|
||||
|
||||
编写一个简单的逆波兰式计算器,它接受用户输入的整型数(最大值 999999)和运算符 +、-、*、/。
|
||||
编写一个简单的逆波兰式计算器,它接受用户输入的整型数(最大值 999999)和运算符 +、-、\*、/。
|
||||
输入的格式为:number1 ENTER number2 ENTER operator ENTER --> 显示结果
|
||||
当用户输入字符 'q' 时,程序结束。请使用您在练习11.3中开发的 `stack` 包。
|
||||
|
||||
|
||||
## 链接
|
||||
|
||||
- [目录](directory.md)
|
||||
|
Reference in New Issue
Block a user