func (*Reader) 读取字符串
func (b *Reader) ReadString(delim byte) (string, error)
ReadString 读取直到输入中第一次出现 delim,返回一个字符串,其中包含直到并包括分隔符的数据。
name
终端输入包括尾随换行符。例如,
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
reader := bufio.NewReader(os.Stdin)
fmt.Print("Enter name:")
name, err := reader.ReadString('\n')
if err != nil {
panic(err)
}
fmt.Printf("%q\n", name)
fmt.Println(name == "nixon")
}
输出(Linux):
Enter name:nixon
"nixon\n"
false
输出(视窗):
Enter name:nixon
"nixon\r\n"
false
修剪尾随换行符。例如,
package main
import (
"bufio"
"fmt"
"os"
"strings"
)
func main() {
reader := bufio.NewReader(os.Stdin)
fmt.Print("Enter name:")
name, err := reader.ReadString('\n')
if err != nil {
panic(err)
}
fmt.Printf("%q\n", name)
name = strings.TrimRight(name, "\r\n")
fmt.Printf("%q\n", name)
fmt.Println(name == "nixon")
}
输出(Linux):
Enter name:nixon
"nixon\n"
"nixon"
true
输出(视窗):
Enter name:nixon
"nixon\r\n"
"nixon"
true