go-键盘或管道文件输入
I am trying to write a function that can read input from the keyboard or read from a piped-in file one line at a time. I already have a function that takes keyboard input similar toprompt()
in this test code:
package main
import (
"fmt"
"bufio"
"os"
)
func print(format string, a ...interface{}) {
fmt.Printf(format+"
", a...)
}
func prompt(format string) string {
fmt.Print(format)
in := bufio.NewScanner(os.Stdin)
in.Scan()
return in.Text()
}
func greet() {
name := prompt("enter name: ")
print(`Hello %s!`, name)
}
func humor() {
color := prompt("enter favorite color: ")
print(`I like %s too!`, color)
}
func main() {
greet()
humor()
}
Here,greet()
andhumor()
both useprompt()
to get the input, and if I run the program and type in the responses, it will work as expected. However, if I have a filea.txt
:
bobby bill
soft, blue-ish turquoise
and then run:.\test< a.txt
, the program will output:
enter name: Hello bobby bill!
enter favorite color: I like too!
instead of:
enter name: Hello bobby bill!
enter favorite color: I like soft, blue-ish turquoise too!
As I understand it, this is because thebufio.Scanner
that was made ingreet()
read all ofa.txt
. I can solve this problem easily by making thebufio.Scanner
a global variable and haveprompt()
use that instead of creating a newbufio.Scanner
each time, but I am wondering if there is a better way to do this without having to resort to global variables.
本文由 创作,采用 知识共享署名4.0 国际许可协议进行许可。本站文章除注明转载/出处外,均为本站原创或翻译,转载前请务必署名。最后编辑时间为: 2020/08/29 08:00