go-键盘或管道文件输入

/ go / 没有评论 / 1742浏览

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.Scannerthat was made ingreet()read all ofa.txt. I can solve this problem easily by making thebufio.Scannera global variable and haveprompt()use that instead of creating a newbufio.Scannereach time, but I am wondering if there is a better way to do this without having to resort to global variables.