August 19, 2015

Go Scan, Scanf, Scanln, ReadString

In go, 4 methods are commonly used for read from stdin.
Scan, Scanf, Scanln, ReadString.

They are different in that:

Read from stdin in go is rather different from that of python. Following issues need to be taken care of.

import (

var stdin *bufio.Reader
func init() {
	stdin = bufio.NewReader(os.Stdin)

func input() string {
	s, _ := stdin.ReadString('\n')
	return strings.TrimRight(s, "\n")

A better way to scan line by line is

scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
  • LinkedIn
  • Tumblr
  • Reddit
  • Google+
  • Pinterest
  • Pocket