go圣经里有一段`查找重复的行`的代码,发现输入无反应不会打印重复行数据
``` go
// Dup1 prints the text of each line that appears more than
// once in the standard input, preceded by its count.
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
counts := make(map[string]int)
input := bufio.NewScanner(os.Stdin)
for input.Scan() {
counts[input.Text()]++
}
if input.Err() != nil{
fmt.Print("err")
} // NOTE: ignoring potential errors from input.Err()
for line, n := range counts {
if n > 1 {
fmt.Printf("%d\t%s\n", n, line)
}
}
}
```
其实是`input.Scan()` 这个循环里面没有跳出,程序会一直监听输入信息,只要加个中断跳出就非常明白了:
``` go
// Dup1 prints the text of each line that appears more than
// once in the standard input, preceded by its count.
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
counts := make(map[string]int)
input := bufio.NewScanner(os.Stdin)
for input.Scan() {
// 控制循环退出
if input.Text() == "end" { break }
counts[input.Text()]++
}
if input.Err() != nil{
fmt.Print("err")
}
// NOTE: ignoring potential errors from input.Err()
for line, n := range counts {
if n > 1 {
fmt.Printf("%d\t%s\n", n, line)
}
}
}
```
再次输入
```go
go run ch1/dup1/main.go
a
a
b
b
c
end
```
输出
```go
2 a
2 b
```
有疑问加站长微信联系(非本文作者))