In go, 4 methods are commonly used for read from stdin.
Scan, Scanf, Scanln, ReadString.
They are different in that:
- Scan read space separated values into successive arguments.
- Scanln also read space separated values into successive arguments, but terminate until a new line is reached.
- Scanf does the same, but is uses the its first parameter as format string to read the values in the variables.
- ReadString read string until some character is reached.
Read from stdin in go is rather different from that of python. Following issues need to be taken care of.
- Use Scan* in inner loop is a bad idea. The internals of scan* do some state bookkeeping on every call.
- ReadString contain tailling
\n
. If you want the standard python input() behavior. The following may be useful for you.
import (
"strings"
"bufio"
"os"
)
var stdin *bufio.Reader
func init() {
stdin = bufio.NewReader(os.Stdin)
}
func input() string {
s, _ := stdin.ReadString('\n')
return strings.TrimRight(s, "\n")
}
- Atoi fail if string has tailling \n
A better way to scan line by line is
scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
fmt.Println(scanner.Text())
}