Search code examples
gosplitscanfstdin

Golang reading multiple fields from stdin line


$ echo "A 1 2 3 4" | go run test.go 
entire:  A
next field:  A

I need to read several lines from standard input that are like "A 1 2 3 4" (code does one line for now) and something goes wrong. Scanln should read the entire line and Fields should split it by newlines? Why does Scanln read only one word?

package main

import (
    "fmt"
    "strings"
)

func main() {
    var line string
    fmt.Scanln(&line)
    fmt.Println("entire: ",line)
    for _,x := range strings.Fields(line) {
        fmt.Println("next field: ",x)
    }
}

$ echo "A 1 2 3 4" | go run test.go 
entire:  A
next field:  A

Solution

  • Have you tried:

    package main
    
    import (
        "fmt"
        "os"
        "bufio"
        "strings"
    )
    
    func main() {
        var line string
        scanner := bufio.NewScanner(os.Stdin)
        for scanner.Scan() {
            line = scanner.Text()
            fmt.Println("Got line:", line)
            for _, x := range strings.Fields(line) {
                fmt.Println("next field: ",x)
            }
        }
    }
    

    Then:

    $ printf "aa bb \n cc dd " | go run 1.go  
    Got line: aa bb
    next field:  aa
    next field:  bb
    Got line:  cc dd
    next field:  cc
    next field:  dd