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 微信小程序 用oss下载 aliyun-oss-sdk-6.18.0.min client报错
  • ¥15 ArcGIS批量裁剪
  • ¥15 labview程序设计
  • ¥15 为什么在配置Linux系统的时候执行脚本总是出现E: Failed to fetch http:L/cn.archive.ubuntu.com
  • ¥15 Cloudreve保存用户组存储空间大小时报错
  • ¥15 伪标签为什么不能作为弱监督语义分割的结果?
  • ¥15 编一个判断一个区间范围内的数字的个位数的立方和是否等于其本身的程序在输入第1组数据后卡住了(语言-c语言)
  • ¥15 Mac版Fiddler Everywhere4.0.1提示强制更新
  • ¥15 android 集成sentry上报时报错。
  • ¥15 抖音看过的视频,缓存在哪个文件