清风徐来
Michael's Blog
Go从Console读取输入

请输入图片描述 ##一个简单的shell 一个示例的shell,没啥用:

package main

import (
	"bufio"
	"fmt"
	"os"
	"strings"
)

func main() {

	reader := bufio.NewReader(os.Stdin)
	fmt.Println("Simple Shell")
	fmt.Println("---------------------")

	for {
		fmt.Print("-> ")
		text, _ := reader.ReadString('\n')
		// 将CRLF转换为LF
		text = strings.Replace(text, "\n", "", -1)
		// 如果windows,要用下面的
		// text = strings.Replace(text, "\r\n", "", -1)

		if strings.Compare("hi", text) == 0 {
			fmt.Println("hello, Yourself")
		}

		if strings.Compare("bye", text) == 0 {
			fmt.Println("Bye.")
			break
		}

	}

}

输入hi,它会打个招呼;输入bye,退出shell。

##读取单个UTF-8编码的Unicode字符

package main

import (
	"bufio"
	"fmt"
	"os"
)

func main() {

	reader := bufio.NewReader(os.Stdin)
	char, _, err := reader.ReadRune()

	if err != nil {
		fmt.Println(err)
	}

	// 打印出unicode值,即 A -> 65, a -> 97, 杨 -> 26472
	fmt.Println(char)

	switch char {
	case 'A':
		fmt.Println("A Key Pressed")
		break
	case 'a':
		fmt.Println("a Key Pressed")
		break
	}
}

杨的unicode是26472.

##小结 学习来bufio的一些用法,还穿插了一些流程控制语句,if,for,switch。


最后修改于 2019-07-29