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 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了