// Chapter 21 example: the input-reading lines, in functions of their own. // Run with: go run exercises/21/08-read-functions.go package main import ( "bufio" "fmt" "os" "strconv" "strings" ) var reader = bufio.NewReader(os.Stdin) // readLine prints the prompt and gives back one trimmed line. The error is // not nil when there is no more input. func readLine(prompt string) (string, error) { fmt.Print(prompt) text, err := reader.ReadString('\n') line := strings.TrimSpace(text) if err != nil && line == "" { return "", err } return line, nil } // readInt asks until it gets a whole number. The error is not nil when // there is no more input. func readInt(prompt string) (int, error) { for { line, err := readLine(prompt) if err != nil { return 0, err } number, err := strconv.Atoi(line) if err == nil { return number, nil } fmt.Println("That is not a whole number.") } } func main() { a, err := readInt("First number: ") if err != nil { fmt.Println("No more input.") return } b, err := readInt("Second number: ") if err != nil { fmt.Println("No more input.") return } fmt.Printf("Sum: %d\n", a+b) }