Golang的交互模式進階-讀取用戶的輸入


                  Golang的交互模式進階-讀取用戶的輸入

                                          作者:尹正傑

版權聲明:原創作品,謝絕轉載!否則將追究法律責任。

 

  讀寫數據除了 fmt 和 os 包,我們還需要用到 bufio 包來處理緩沖的輸入和輸出。

 

一.從控制台讀取輸入

  我們如何讀取用戶的鍵盤(控制台)輸入呢?從鍵盤和標准輸入 os.Stdin 讀取輸入,最簡單的辦法是使用 fmt 包提供的 Scan 和 Sscan 開頭的函數。具體代碼如下

 1 /*
 2 #!/usr/bin/env gorun
 3 @author :yinzhengjie
 4 Blog:http://www.cnblogs.com/yinzhengjie/tag/GO%E8%AF%AD%E8%A8%80%E7%9A%84%E8%BF%9B%E9%98%B6%E4%B9%8B%E8%B7%AF/
 5 EMAIL:y1053419035@qq.com
 6 */
 7 
 8 package main
 9 import "fmt"
10 var (
11     FirstName, SecondNames, ThirdNames string
12     i int
13     f float32
14     Input = "5.2 / 100 / Golang"        //用戶自定義變量,便於之后對這個字符串的處理。
15     format = "%f / %d / %s"
16 )
17 func main() {
18     fmt.Printf("Please enter your full name: ")
19     fmt.Scanln(&FirstName, &SecondNames)    //Scanln 掃描來自標准輸入的文本,將空格分隔的值依次存放到后續的參數內,直到碰到換行。
20     // fmt.Scanf("%s %s", &firstName, &lastName)    //Scanf與其類似,除了 Scanf 的第一個參數用作格式字符串,用來決定如何讀取。
21 
22     fmt.Printf("Hi %s %s!\n", FirstName, SecondNames)
23     fmt.Sscanf(Input, format, &f, &i, &ThirdNames)    //Sscan 和以 Sscan 開頭的函數則是從字符串讀取,除此之外,與 Scanf 相同。如果這些函數讀取到的結果與您預想的不同,您可以檢查成功讀入數據的個數和返回的錯誤。
24 
25     fmt.Println("From the Input we read: ", f, i, ThirdNames)
26 }
27 
28 
29 
30 #以上代碼執行結果如下:
31 Please enter your full name: yinzhengjie
32 Hi yinzhengjie !
33 From the Input we read:  5.2 100 Golang

 

二.從緩沖讀取輸入

  bufio.NewReader() 構造函數的簽名為: func NewReader(rd io.Reader) *Reader。該函數的實參可以是滿足 io.Reader 接口的任意對象,函數返回一個新的帶緩沖的 io.Reader 對象,它將從指定讀取器(例如 os.Stdin )讀取內容。返回的讀取器對象提供一個方法 ReadString(delim byte) ,該方法從輸入中讀取內容,直到碰到 delim指定的字符,然后將讀取到的內容連同 delim 字符一起放到緩沖區。ReadString 返回讀取到的字符串,如果碰到錯誤則返回 nil 。如果它一直讀到文件結束,則返回讀取到的字符串和 io.EOF 。如果讀取過程中沒有碰到 delim 字符,將返回錯誤 err != nil 。

 1 /*
 2 #!/usr/bin/env gorun
 3 @author :yinzhengjie
 4 Blog:http://www.cnblogs.com/yinzhengjie/tag/GO%E8%AF%AD%E8%A8%80%E7%9A%84%E8%BF%9B%E9%98%B6%E4%B9%8B%E8%B7%AF/
 5 EMAIL:y1053419035@qq.com
 6 */
 7 
 8 package main
 9 
10 import (
11     "fmt"
12     "bufio"
13     "os"
14 )
15 
16 var (
17     inputReader *bufio.Reader //inputReader 是一個指向 bufio.Reader 的指針。
18     input string
19     err error
20 )
21 func main() {
22     inputReader = bufio.NewReader(os.Stdin)    //創建一個讀取器,並將其與標准輸入綁定。
23     fmt.Printf("Please enter some input: ")
24     input, err = inputReader.ReadString('\n') //讀取器對象提供一個方法 ReadString(delim byte) ,該方法從輸入中讀取內容,直到碰到 delim 指定的字符,然后將讀取到的內容連同 delim 字符一起放到緩沖區。
25     if err == nil {
26         fmt.Printf("The input was: %s", input)
27     }
28 }
29 
30 
31 
32 #以上代碼執行結果如下:
33 Please enter some input: yinzhengjie
34 The input was: yinzhengjie

 

三.從鍵盤讀取輸入

   使用了 switch 語句來判斷用戶輸入的字符串。

 1 /*
 2 #!/usr/bin/env gorun
 3 @author :yinzhengjie
 4 Blog:http://www.cnblogs.com/yinzhengjie/tag/GO%E8%AF%AD%E8%A8%80%E7%9A%84%E8%BF%9B%E9%98%B6%E4%B9%8B%E8%B7%AF/
 5 EMAIL:y1053419035@qq.com
 6 */
 7 
 8 package main
 9 
10 import (
11     "fmt"
12     "os"
13     "bufio"
14 )
15 
16 func main() {
17     inputReader := bufio.NewReader(os.Stdin)
18     fmt.Printf("Please enter your name:")
19     input, err := inputReader.ReadString('\n')
20     if err != nil {
21         fmt.Println("There were errors reading, exiting program.")
22         return
23     }
24     fmt.Printf("Your name is %s", input)
25     switch input {
26     case "yinzhengjie\n":
27         fmt.Println("Welcome yinzhengjie!")
28     case "bingan\n":
29         fmt.Println("Welcome bingan!")
30     case "liufei\n":
31         fmt.Println("Welcome liufei")
32     default:
33         fmt.Println("You are not welcome here! Goodbye!")
34     }
35 /*    //version 2:
36     switch input {
37     case "yinzhengjie\n":
38         fallthrough
39     case "jiashanpeng\n":
40         fallthrough
41     case "hansenyu\n":
42         fmt.Printf("Welcome %s\n", input)
43     default:
44         fmt.Printf("You are not welcome here! Goodbye!\n")
45     }
46 
47     // version 3:
48     switch input {
49     case "yinzhengjie\n", "wuzhiguang\n":
50         fmt.Printf("Welcome %s", input)
51     default:
52         fmt.Printf("You are not welcome here! Goodbye!\n")
53     }
54 
55 */
56 
57 }
58 
59 
60 
61 #以上代碼執行結果如下:
62 Please enter your name:yinzhengjie
63 Your name is yinzhengjie
64 Welcome yinzhengjie!

 

四.小試牛刀

  以下是一個和用戶進行交互的程序,將用戶輸入的字符串和數字進行打印,相當於一個echo的一個功能,具體需要打印的類型需要自行修改。

 1 /*
 2 #!/usr/bin/env gorun
 3 @author :yinzhengjie
 4 Blog:http://www.cnblogs.com/yinzhengjie/tag/GO%E8%AF%AD%E8%A8%80%E7%9A%84%E8%BF%9B%E9%98%B6%E4%B9%8B%E8%B7%AF/
 5 EMAIL:y1053419035@qq.com
 6 */
 7 
 8 
 9 package main
10 
11 import (
12     "bufio"
13     "os"
14     "fmt"
15 )
16 
17 var   (
18     String string
19     Number int
20     Input string
21 )
22 
23 func main()  {
24     f := bufio.NewReader(os.Stdin) //讀取輸入的內容
25     for {
26         fmt.Print("請輸入一些字符串>")
27         Input,_ = f.ReadString('\n') //定義一行輸入的內容分隔符。
28         if len(Input) == 1 {
29             continue //如果用戶輸入的是一個空行就讓用戶繼續輸入。
30         }
31         fmt.Printf("您輸入的是:%s",Input)
32         fmt.Sscan(Input,&String,&Number) //將Input
33         if String == "stop" {
34             break
35         }
36         fmt.Printf("您輸入的第一個參數是:·\033[31;1m%v\033[0m·,輸入的第二個參數是··\033[31;1m%v\033[0m·.\n",String,Number)
37     }
38 }
39 
40 
41 #以上代碼執行結果如下:
42 請輸入一些字符串>yinzhengjie 123
43 您輸入的是:yinzhengjie 123
44 您輸入的第一個參數是:·yinzhengjie·,輸入的第二個參數是··123·.
45 請輸入一些字符串>
46 請輸入一些字符串>
47 請輸入一些字符串>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM