golang对于输入的处理,在我看来是非常方便的。今年的秋招笔试,果断弃c++了。

首先来讲一下几种简单的输入处理。

一·从控制台读取输入

1. fmt.Scan

fmt.Scan交互式接受输入,通过空格来分词。调用Scan函数时,要指定接收输入的变量名和变量数。

直到接收完所有指定的变量数,Scan函数才会返回,回车符也无法提前让它返回。

fmt.Println("Please enter the firstName and secondName: ")

fmt.Scan(&afirstName, &asecondName)

fmt.Printf("firstName is %s, secondName is %s\n", afirstName, asecondName)

结果如下:

Please enter the firstName and secondName:

zz

rr

firstName is zz, secondName is rr

2. fmt.Scanln

Scanln调用时,也要指定接收输入的变量名和变量数。

它同Scan的区别,在于 \ n 会让函数提前返回,将返回时还未接收到值的变量赋为空。

fmt.Println("Please enter the firstName and secondName: ")

fmt.Scanln(&bfirstName, &bsecondName)

fmt.Printf("firstName is %s, secondName is %s\n", bfirstName, bsecondName)

结果如下:

Please enter the firstName and secondName:

zr

firstName is zr, secondName is

3. fmt.Scanf

用Scanf处理输入,是比较灵活的一种处理方式。

需要指定输入的格式,适用于完全了解输入格式的场景,可以直接把不需要的部分过滤掉。

fmt.Println("Please enter the firstName and secondName: ")

fmt.Scanf("//%s //%s //%s", &cfirstName, &csecondName, &clastName)

fmt.Printf("firstName is %s, secondName is %s, lastname is %s", cfirstName, csecondName, clastName)

结果如下:

1)这个场景,在接收输入时,就把不需要的部分“//” 过滤掉了,接收到是有用的三个字符串。

Please enter the firstName and secondName:

//a //b //c

firstName is a, secondName is b, lastname is c

2)如果输入不符合指定的格式,从不符合处开始,其后的变量值都为空。

Please enter the firstName and secondName:

//A //b uiojhk

firstName is A, secondName is b, lastname is

值得一提的是:

1)此处的空格部分格外有趣。

fmt.Scanf("//%s          //%s //%s", &cfirstName, &csecondName, &clastName)

Please enter the firstName and secondName:

//a //b              //c

firstName is a, secondName is b, lastname is c

不管是scanf中格式化部分的空格,还是输入时的空格,多个空格都会被自动缩减成一个。

2)需要过滤的部分,与前面的占位符间一定要有空格

fmt.Scanf("%s, %s", &cfirstName, &csecondName)

Please enter the firstName and secondName:

a, b

firstName is a,, secondName is


二·从缓存读取输入

1. bufio.NewReader函数,参数可以是实现了io.Reader接口的任意对象,返回值为一个指向 bufio.Reader 的指针。

从而创建了一个读取器inputReader。

inputReader会从指定处读取数据,此处inputReader与os.Stdin绑定好了。因此读取器中读入的数据,就是标准输入。

ReadString方法从输入中读取内容,直到碰到 delim 指定的字符,然后将读取到的内容连同 delim 字符一起放到缓冲区。

ReadString 返回读取到的字符串,如果在读取到delim前遇到了error,返回遇到error读到的数据和error本身;当且仅当返回的数据不以delim结尾时,返回err != nil

inputReader := bufio.NewReader(os.Stdin)

fmt.Println("Please enter the input: ")

// input, err := inputReader.ReadSlice('a')

input, err := inputReader.ReadString('a')

if err == nil {

fmt.Printf("The input is %s", input)

}

结果如下:

Please enter the input:

ouyuiyhafff

The input is ouyuiyha