请原谅我从Go开始,我正在学习bufio软件包,但是每次我使用Scanner类型时,命令行都会卡在输入中,并且不会继续正常的程序流程。我试过按Enter键,但它一直在换行。
这是我的代码。
/*
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",n,line)
}
}
}
Run Code Online (Sandbox Code Playgroud)
您有一个for循环,可从标准输入中读取行。只要os.Stdin不报告io.EOF,此循环将一直运行(这是Scanner.Scan()返回时的一种情况false)。通常这不会发生。
如果你想以“模拟”输入结束后,按Ctrl+ Z在Windows,或Ctrl+ D在Linux / Unix系统。
因此,输入一些行(每个行都用“关闭” Enter),完成后,按上述键。
输出示例:
Type Some Text
a
a
bb
bb
bbb <-- CTRL+D pressed here
2 a
2 bb
Run Code Online (Sandbox Code Playgroud)
另一种选择是使用“特殊”字词来终止,例如"exit"。它可能看起来像这样:
for input.Scan() {
line := input.Text()
if line == "exit" {
break
}
counts[line]++
}
Run Code Online (Sandbox Code Playgroud)
测试它:
Type Some Text
a
a
bb
bb
bbb
exit
2 a
2 bb
Run Code Online (Sandbox Code Playgroud)