golang中使用bufio.Scanner时如何继续执行程序

How to continue program execution when using bufio.Scanner in golang

请原谅我刚开始使用 Go,我正在学习 bufio 包,但每次我使用 Scanner 类型时,命令行都会卡在输入上,无法继续正常的程序流程。我试过按 Enter 键,但它总是换行。

这是我的代码。

/*
Dup 1 prints the text of each line that appears more than
once in the standard input, proceeded by its count.
*/
package main

import(
  "bufio"
  "fmt"
  "os"
)

func main(){
  counts := make(map[string]int)
  fmt.Println("Type Some Text")
  input := bufio.NewScanner(os.Stdin)

  for input.Scan(){
    counts[input.Text()]++
  }
  //NOTE: Ignoring potential Errors from  input.Err()

  for line,n := range counts{
    if n > 1{
      fmt.Printf("%d \t %s \n",n,line)
    }
  }
}

你有一个 for 循环,它从标准输入中读取行。只要 os.Stdin 不报告 io.EOF,此循环就会 运行(这是 Scanner.Scan() 会 return false 的一种情况)。通常这不会发生。

如果要"simulate"输入结束,按Ctrl+Z on Windows,或 Ctrl+D 在 Linux / unix 系统上。

因此输入一些行(每行 "closed" 按 Enter),完成后,按上面提到的键。

示例输出:

Type Some Text
a
a
bb
bb 
bbb                               <-- CTRL+D pressed here
2        a 
2        bb 

另一种选择是使用 "special" 词作为终止词,例如 "exit"。它可能看起来像这样:

for input.Scan() {
    line := input.Text()
    if line == "exit" {
        break
    }
    counts[line]++
}

正在测试:

Type Some Text
a
a
bb
bb
bbb
exit
2        a 
2        bb