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

在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 求chat4.0解答一道线性规划题,用lingo编程运行,第一问要求写出数学模型和lingo语言编程模型,第二问第三问解答就行,我的ddl要到了谁来求了
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥15 maple软件,用solve求反函数出现rootof,怎么办?
  • ¥65 汇编语言除法溢出问题
  • ¥15 Visual Studio问题
  • ¥20 求一个html代码,有偿
  • ¥100 关于使用MATLAB中copularnd函数的问题
  • ¥20 在虚拟机的pycharm上
  • ¥15 jupyterthemes 设置完毕后没有效果