查找重复的行(程序无响应?)[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() 这个循环里面没有跳出,程序会一直监听输入信息,只要加个中断跳出就非常明白了:

// 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 run ch1/dup1/main.go 
a
a  
b
b
c
end

输出

2       a
2       b

你可能感兴趣的:(golang,input)