go语言如何从终端逐行读取数据? 来看看:
package main
import ("fmt"
"os"
"bufio")
func main(){
counts := make(map[string] int)
input := bufio.NewScanner(os.Stdin)
for input.Scan(){
s := input.Text()
fmt.Printf("cur line is %s\n", s)
counts[s]++
}
for line, n := range counts{
if n > 1 {
fmt.Printf("%d %s\n", n, line);
}
}
}
开看看在终端上的执行:
ubuntu@VM-0-15-ubuntu:~/taoge/go$ ./test
123
cur line is 123
456
cur line is 456
123
cur line is 123
2 123
ubuntu@VM-0-15-ubuntu:~/taoge/go$
上述程序的for循环是怎么退出的呢? 在linux上, 按ctrl + d吧, 让input.Scan函数返回false.
练练手, 不多说。