关于如何使用stdin,现举两个例子演示其使用。
example1
直接从os.Stdin中读取
@H_404_6@package main import ( "fmt" "os" ) func main() { var buffer [512]byte n,err := os.Stdin.Read(buffer[:]) if err != nil { fmt.Println("read error:",err) return } fmt.Println("count:",n,",msg:",string(buffer[:])) }output:
$ ./test
Hello
count: 6,msg: Hello
example2
通过bufio读取
@H_404_6@package main import ( "bufio" "fmt" "os" ) func main() { reader := bufio.NewReader(os.Stdin) result,err := reader.ReadString('\n') if err != nil { fmt.Println("read error:",err) } fmt.Println("result:",result) }output:
$ ./test
nihao
result: nihao
更多信息可参考os package说明:
http://docs.studygolang.com/pkg/os/