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

时间:2019-01-04 10:28:26

标签: go stdin

请原谅我从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)
    }
  }
}

1 个答案:

答案 0 :(得分:4)

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

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

因此,输入一些行(每行用 Enter “关闭”),完成后,按上述键。

示例输出:

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

另一种选择是使用“特殊”字词来终止,例如"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