scanf or std::cin in go

1,044 views
Skip to first unread message

Andrea

unread,
Mar 10, 2010, 7:41:53 AM3/10/10
to golang-nuts
Hi!
Is there a function that works like C scanf (or C++ std::cin) in GO
library?
If not, how can I capture the input in GO?
Sorry for the simple question and for my (bad) english!

Ostsol

unread,
Mar 10, 2010, 7:53:59 AM3/10/10
to golang-nuts
There is a scanner package that parses strings and returns individual
tokens. I've never used it, though, so I can't give an example, at
the moment.

For capturing console input, you simply have to read from os.Stdin.

-Daniel

Andrea

unread,
Mar 10, 2010, 9:12:12 AM3/10/10
to golang-nuts
Thanks. I created a simple function Input similar to Python in a
package called "scan". Can I improve it?

package scan

import ("bufio"; "os")

func Input(str string) string {
print(str)
reader := bufio.NewReader(os.Stdin)
input, _ := reader.ReadString('\n')
return input

Russ Cox

unread,
Mar 10, 2010, 1:35:02 PM3/10/10
to Andrea, golang-nuts
On Wed, Mar 10, 2010 at 06:12, Andrea <azza...@gmail.com> wrote:
> Thanks. I created a simple function Input similar to Python in a
> package called "scan". Can I improve it?

Yes. It would work better to do a single bufio.NewReader
and then repeatedly call ReadString. Reading from a bufio.Reader
can read beyond what it returns (it has a buffer), so as written
this Input function will skip over chunks of data when stdin
is a file, because the buffer is discarded every time Input returns.

> func Input(str string) string {
>        print(str)
>        reader := bufio.NewReader(os.Stdin)
>        input, _ := reader.ReadString('\n')
>        return input
> }

Russ

Reply all
Reply to author
Forward
0 new messages