Go: os: Add example showing how to read data from stdin

Created on 24 Oct 2017  ·  4Comments  ·  Source: golang/go

A pretty common task, especially for new programmers, is to ask the user to type in some value at the command line and then have the program act on it. (think "interactive maze game", "determine if word is palindrome", etc). It would be nice if we had an example in the os package showing how to do this.

Documentation help wanted

Most helpful comment

I don't think a new programmer should use os or bufio to do this.
fmt is much simpler.

package main

import "fmt"

func main() {
    var x, y int
    fmt.Scan(&x, &y)
    fmt.Println(x + y)
}

All 4 comments

I don't think that belongs in the os package documentation (a new programmer is unlikely to look there first for help). What you suggest would belong more in a tutorial, like the Go tour, which already has a lot of basic examples, though nothing about reading console input.

Ideally we'd add it in both places.

If this hasn't been taken yet, I should be able to do this. The line example (provided here: https://golang.org/pkg/bufio/#Scanner) is perfect for what I think you are looking for. I may adapt the example but it should be a pretty quick addition to the docs...

I don't think a new programmer should use os or bufio to do this.
fmt is much simpler.

package main

import "fmt"

func main() {
    var x, y int
    fmt.Scan(&x, &y)
    fmt.Println(x + y)
}
Was this page helpful?
0 / 5 - 0 ratings

Related issues

natefinch picture natefinch  ·  3Comments

enoodle picture enoodle  ·  3Comments

OneOfOne picture OneOfOne  ·  3Comments

rsc picture rsc  ·  3Comments

myitcv picture myitcv  ·  3Comments