In Go, write a readInt
function to hide the complexity and always check for errors. Other answers have bugs: Howl (drops last number) and Raduan Santos (doesn't compile).
For example,
package main
import (
"bufio"
"fmt"
"io"
"log"
"strconv"
"strings"
)
func readInt(r *bufio.Reader) (int, error) {
const delim = ' '
str, err := r.ReadString(delim)
if err != nil && len(str) == 0 {
return 0, err
}
str = strings.TrimSuffix(str, string(delim))
return strconv.Atoi(str)
}
func main() {
input := "93 31 11 11"
fmt.Println(input)
rdr := bufio.NewReader(strings.NewReader(input))
for {
n, err := readInt(rdr)
if err != nil {
if err == io.EOF {
break
}
log.Fatal(err)
}
fmt.Println(n)
}
}
Output:
93 31 11 11
93
31
11
11