• 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!
    ", 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('
    ') //读取器对象提供一个方法 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('
    ')
    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
    ":
    27         fmt.Println("Welcome yinzhengjie!")
    28     case "bingan
    ":
    29         fmt.Println("Welcome bingan!")
    30     case "liufei
    ":
    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
    ":
    38         fallthrough
    39     case "jiashanpeng
    ":
    40         fallthrough
    41     case "hansenyu
    ":
    42         fmt.Printf("Welcome %s
    ", input)
    43     default:
    44         fmt.Printf("You are not welcome here! Goodbye!
    ")
    45     }
    46 
    47     // version 3:
    48     switch input {
    49     case "yinzhengjie
    ", "wuzhiguang
    ":
    50         fmt.Printf("Welcome %s", input)
    51     default:
    52         fmt.Printf("You are not welcome here! Goodbye!
    ")
    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('
    ') //定义一行输入的内容分隔符。
    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("您输入的第一个参数是:·33[31;1m%v33[0m·,输入的第二个参数是··33[31;1m%v33[0m·.
    ",String,Number)
    37     }
    38 }
    39 
    40 
    41 #以上代码执行结果如下:
    42 请输入一些字符串>yinzhengjie 123
    43 您输入的是:yinzhengjie 123
    44 您输入的第一个参数是:·yinzhengjie·,输入的第二个参数是··123·.
    45 请输入一些字符串>
    46 请输入一些字符串>
    47 请输入一些字符串>
  • 相关阅读:
    【简】题解 AWSL090429 【市场】
    【简】题解 AWSL090429 【噪音】
    差分约束
    凸包模板
    杂模板
    后缀数组刷题
    Trie刷题
    字符串模板
    网络流建模专题
    组合数模板
  • 原文地址:https://www.cnblogs.com/yinzhengjie/p/7798498.html
Copyright © 2020-2023  润新知