除了f
mt
和
os
,咱們還須要用到
bufio
來實現帶緩衝輸入(input)和輸出(output)
讀取用戶的輸入數據
咱們怎樣讀取用戶從鍵盤(控制檯)輸入的數據?輸入指從鍵盤或其它標準輸入(os.Stdin)讀取數據。最簡單的方法是使用fmt包裏的Scan-或Sscan-系列函數,下面用個例子說明一下:
//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 input your full name: ")
fmt.Scanln(&firstName, &lastName)
// fmt.Scanf(「%s %s」, &firstName, &lastName)
fmt.Printf("Hi %s %s!\n", firstName, lastName)
fmt.Sscanf(input, format, &f, &i, &s)
fmt.Println("From the string we read: ", f, i, s)
}
Scanln 將從標準輸入的帶有空格的字符串值保存到相應的變量裏去,並以一個新行結束輸入,
Scanf作相同的工做,但它使用第一個參數指時輸入格式,
Sscan系列函數也是讀取輸入,但它是用來從字符串變量裏讀取,而不是從標準(os.Stdin)裏讀取
另外,咱們也能夠使用
bufio包裏帶緩衝的reader,例如
//////////
package main
import (
"bufio"
"fmt"
"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('S') //func (b *Reader) ReadString(delim byte) (line string, err error) ,‘S’ 這個例子裏使用S表示結束符,也能夠用其它,如'\n'
if err == nil {
fmt.Printf("The input was: %s\n", input)
}
}
Please enter some input:
abcd
abc
S
The input was: abcd
abc
S
上例中,inputReader 是個指針,它指向一個
bufio類的Reader,而後在main函數裏,經過了bufio.NewReader(os.Stdin)建立了一個buffer reader, 並聯接到inputReader這個變量。bufio.NewReader()
構造器的原型是這樣的
func NewReader(rd io.Reader) *Reader
任何符合io.Reader接口的對象(即實現了Read()方法對象)均可以做爲bufio.NewReader()裏的參數,並返回一個新的帶緩衝的io.Reader, os.Stdin 符合這個條件。這個帶緩衝的reader有一個方法ReadString(delim byte), 這個方法會一直讀數據,直到遇到了指定的終止符,終止符將成爲輸入的一部分,一塊兒放到buffer裏去。
ReadString 返回的是讀到的字符串及nil;當讀到文件的末端時,將返回把讀到的字符串及io.EOF,若是在讀到結束時沒有發現所指定的結束符(delim byte),將返回一個 err !=nil 。在上面的例子中,咱們從鍵盤輸入直到鍵入「S」。屏幕是標準輸出os.Stdout,錯誤信息被寫到os.Stderr,大多狀況下,os.Stderr等同os.Stdout。
通常狀況下,在GO的代碼裏,裏省略了變量聲明,而直接使用」:=「也聲明,如:
inputReader := bufio.NewReader(os.Stdin)
input ,err :=inputReader.ReadString('\n')
下面的例子是使用了帶關鍵字switch的,注意Go 的switch的幾種形式以及unix和windows下不一樣的定界符。
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
inputReader := bufio.NewReader(os.Stdin)
fmt.Println("please input your name:")
input, err := inputReader.ReadString('\n')
if err != nil {
fmt.Println("There ware errors reading,exiting program.")
return
}
fmt.Printf("Your name is %s", input)
//對unix:使用「\n」做爲定界符,而window使用"\r\n"爲定界符
//Version1
/*
switch input {
case "Philip\r\n":
fmt.Println("Welcome Philip!")
case "Chris\r\n":
fmt.Println("Welcome Chris!")
case "Ivo\r\n":
fmt.Println("Welcome Ivo!")
default:
fmt.Println("You are not welcome here! Goodbye!")
}
*/
//version2
/*
switch input {
case "Philip\r\n":
fallthrough
case "Ivo\r\n":
fallthrough
case "Chris\r\n":
fmt.Printf("Welcome %s\n", input)
default:
fmt.Printf("You are not welcome here! Goodbye!")
}
*/
//version3
switch input {
case "Philip\r\n", "Ivo\r\n", "Chris\r\n":
fmt.Printf("Welcome %s\n", input)
default:
fmt.Println("You are not welcome here! Goodbye!")
}
}