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

在golang中使用bufio.Scanner时如何继续执行程序,go,stdin,Go,Stdin,请原谅,我从Go开始,我正在学习bufio软件包,但每次我使用扫描仪类型时,命令行都卡在输入上,无法继续正常的程序流程。我试过按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

请原谅,我从Go开始,我正在学习bufio软件包,但每次我使用扫描仪类型时,命令行都卡在输入上,无法继续正常的程序流程。我试过按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()
将返回
false
的一种情况),此循环就会运行。通常这不会发生

如果要“模拟”输入结束,请在Windows上按Ctrl+Z,或在Linux/unix系统上按Ctrl+D

因此,输入一些行(每个行都通过enter“关闭”),完成后,按上述键

示例输出:

Type Some Text
a
a
bb
bb 
bbb                               <-- CTRL+D pressed here
2        a 
2        bb 
测试它:

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