키보드에서 입력을 읽거나 한 번에 한 줄씩 파이프 입력 파일에서 읽을 수있는 함수를 작성하려고합니다. 이미이 테스트 코드에서 prompt()
유사한 키보드 입력을받는 함수가 있습니다go 키보드 또는 파이프 파일 입력
package main
import (
"fmt"
"bufio"
"os"
)
func print(format string, a ...interface{}) {
fmt.Printf(format+"\n", 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()
}
여기
, greet()
및 humor()
가 모두 입력을 얻을 수 prompt()
를 사용을, 나는 응답에서 프로그램 및 유형을 실행하는 경우, 그것을 예상대로 작동합니다. 다음
bobby bill
soft, blue-ish turquoise
실행 : I 파일 a.txt
있는 경우에는 .\test< a.txt
을, 프로그램의 출력 :
enter name: Hello bobby bill!
enter favorite color: I like too!
대신 :
enter name: Hello bobby bill!
enter favorite color: I like soft, blue-ish turquoise too!
내가 알고있는 것처럼,이 greet()
에서 만든 bufio.Scanner
은 모두 a.txt
입니다. 나는 bufio.Scanner
을 전역 변수로 만들어이 문제를 쉽게 해결할 수 있으며, prompt()
은 매번 새로운 bufio.Scanner
을 생성하는 대신에이를 사용하지만 전역 변수를 사용하지 않고이 작업을 수행하는 것이 더 좋은지 궁금하다.