dongshipang8094
2019-01-04 10:28 阅读 108
已采纳

在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 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 Ctrl+Z on Windows, or Ctrl+D on Linux / unix systems.

    So enter some lines (each "closed" by Enter), 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 
    
    点赞 评论 复制链接分享

相关推荐