dongshipang8094 2019-01-04 10:28
浏览 181
已采纳

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

Forgive me I am starting out in Go and I am learning about the bufio package but every time I use the Scanner type the command line is stuck on the input and does not continue with normal program flow. I have tried pressing Enter but it just keeps going to a new line.

Here is my code.

/*
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,line)
    }
  }
}
  • 写回答

1条回答 默认 最新

  • douchen1924 2019-01-04 10:33
    关注

    You have a for loop which reads lines from the standard input. This loop will run as long as os.Stdin doesn't report io.EOF (that's one case when Scanner.Scan() would return false). Normally this won't happen.

    If you want to "simulate" the end of input, press <kbd>Ctrl</kbd>+<kbd>Z</kbd> on Windows, or <kbd>Ctrl</kbd>+<kbd>D</kbd> on Linux / unix systems.

    So enter some lines (each "closed" by <kbd>Enter</kbd>), and when you're finished, press the above mentioned key.

    Example output:

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

    Another option would be to use a "special" word for termination, such as "exit". It could look like this:

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

    Testing it:

    Type Some Text
    a
    a
    bb
    bb
    bbb
    exit
    2        a 
    2        bb 
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog