go - 我们如何在 golang 中停止 bufio 扫描?

标签 go buffer

停止以下扫描的最佳方法是什么?

     outputReader := io.MultiReader(outReader, errReader)
     scanner := bufio.NewScanner(outputReader)
     for scanner.Scan(){
        scanner.Text():
     }   

最佳答案

如果你卡在连续循环中,按 ENTER 无助于退出 scanner.Scan() 循环,那么试试 ctrl+Z 退出循环。

下面是从控制台获取输入并打印重复行的示例代码。

func main() {
    counts := make(map[string]int)
    scanner := bufio.NewScanner(os.Stdin)
    fmt.Println("Accepting inputs")
    for scanner.Scan() {
        counts[input.Text()]++
    }
    // NOTE: ignoring potential errors from input.Err()
    fmt.Println("Printing output")
    for line, n := range counts {
        if n > 1 {
            fmt.Printf("Count: %d\t Line: %s\n", n, line)
        }
    }
}

控制台输出:

Accepting inputs
Hi
hello
hi
Hi

^Z
Printing output
Count: 2         Line: Hi

我们可以看到,在按下 ctrl+Z 后,scanner.Scan() 退出了循环。

关于go - 我们如何在 golang 中停止 bufio 扫描?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37079639/

相关文章:

C++ 缓冲区操作

flutter - channel : flutter/lifecycle 溢出

sql - 如何从数组中动态生成 SQL 查询列名和值?

javascript - 在 NodeJs 中将此缓冲区转换为 JSON

google-app-engine - 使用 Google App Engine 和 Go 的静态文件

转到 channel : the function of one extra line

node.js - 使用缓冲区或流将 Webshot 传输到 Google Drive,无需存储中间文件?

promise - RxJs 缓冲直到数据库插入( promise )

json - 如何清理golang中的输入数据?

windows - 戈朗 : run default application for a pdf file on windows