Input Scanning using bufio in Go

Read standard input by line:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
import (
    "bufio"
    "os"
    "fmt"
)

func main() {
    // New scanner to read from stdin.
    // By default it reads line. ie. split
    // function defaults to ScanLines.

    in := bufio.NewScanner(os.Stdin)
    for in.Scan() {
        // Read line and print it.
        fmt.Println(in.Text())
    }
}

Read by words:

1
2
3
4
5
6
7
// Set split function to ScanWords before Scan() function.

in.Split(bufio.ScanWords)

for in.Scan() {
    ...
}

Capture an error in scanning:

1
2
3
4
5
// in.Err returns first non-EOF error that was encountered in scanner.

if err := in.Err(); err != nil {
    fmt.Println("ERROR:", err)
}