Read a full line of input in Go
Go's fmt
package has a strict "space-delimited" requirement when reading input. In order to read a full line, you'll need to use a method like this:
package main
import (
"bufio"
"fmt"
"os"
)
// read *all* input up to the newline
func readln(r *bufio.Reader) (string, error) {
var (
isPrefix bool = true
err error = nil
line, ln []byte
)
for isPrefix && err == nil {
line, isPrefix, err = r.ReadLine()
ln = append(ln, line...)
}
return string(ln), err
}
func main() {
in := bufio.NewReader(os.Stdin)
var name string
fmt.Print("Enter your name: ")
name,_ = readln(in)
fmt.Printf("Welcome, %s.\n", name)
}
Written by Damien Radtke
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Go
Authors
Related Tags
#go
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#