Solution Review: Analyzing Input from Keyboard
This lesson discusses the solution to the challenge given in the previous lesson.
We'll cover the following...
We'll cover the following...
package main
import (
"fmt"
"bufio"
"os"
"strings"
)
var nrchars, nrwords, nrlines int
func main() {
nrchars, nrwords, nrlines = 0, 0, 0
inputReader := bufio.NewReader(os.Stdin)
fmt.Println("Please enter some input, type S in the new line to stop: ")
for {
input, err := inputReader.ReadString('\n')
if err != nil {
fmt.Printf("An error occurred: %s\n", err)
return
}
if input == "S\n" { // Windows it is "S\r\n", on Linux it is "S\n"
fmt.Println("Here are the counts:")
fmt.Printf("Number of characters: %d\n", nrchars)
fmt.Printf("Number of words: %d\n", nrwords)
fmt.Printf("Number of lines: %d\n", nrlines)
os.Exit(0)
}
Counters(input)
}
}
func Counters(input string) {
nrchars += len(input) - 2 // -2 for \r\n
// count number of spaces, nr of words is +1
nrwords += strings.Count(input, " ") + 1
nrlines++
}Click the RUN button, and wait for the terminal to start. Type go run main.go and press ENTER.
The variables nrchars, nrwords and nrlines contain the counts we must make: they are declared at line 8, and initialized to 0 at line 11. Then, ...