Answer the question
In order to leave comments, you need to log in
Why doesn't the line input counter work in Go?
Hello! I am reading the book The Go Programming Language (2016) [Kernighan B., Donovan A.], and here in one of the first chapters there is a small example program. I enter all these examples on my PC so that the "muscle memory" fills up and gets used to the syntax. The essence of the program is that it reads the input, and shows how many times you entered a certain text.
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
counts := make(map[string]int)
input := bufio.NewScanner(os.Stdin)
for input.Scan() {
counts[input.Text()]++
}
for line, n := range counts {
if n > 1 {
fmt.Printf("%d - %s", n, line)
}
}
}
Answer the question
In order to leave comments, you need to log in
Попробуйте (win): type имяфайла.txt | go run main.go
Если вводить данные в консоли, то нужно обозначить "конец файла" нажатием Ctrl+Z + Enter.
Либо как-то иначе читать данные с консоли.
добавлю к выше написанному что для unix-подобных признак конца файла будет сочетание клавиш Ctrl+D.
Также для данной задачи можно использовать конвейер:
$ echo "aaaf\nddd\nddd"| go run main.go
2 ddd
if input.Text() == "exit" {
break
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question