How t use fmt.Scan or fmt.Scanln correct

4,594 views
Skip to first unread message

Tobias Matt

unread,
Jul 28, 2011, 6:04:37 PM7/28/11
to golang-nuts
I tried this little program:

package main

import(
"fmt"
)

func main() {
var input string
fmt.Print("Some input please: ")
_, err := fmt.Scanln(&input)
if err != nil {
fmt.Println("Error: ", err)
}

fmt.Println("There's the Output:", input)
}

And it work, if I only give one word as input. But if I insert more
than one word, it returns only the first word and it ocours an error.

How to solve this Problem?

Evan Shaw

unread,
Jul 28, 2011, 6:09:07 PM7/28/11
to Tobias Matt, golang-nuts
On Fri, Jul 29, 2011 at 10:04 AM, Tobias Matt <t.ma...@gmail.com> wrote:
> How to solve this Problem?

This is how it's supposed to work. From the fmt documentation, with
added emphasis:

"Scan scans text read from standard input, storing *successive
space-separated values* into successive arguments."

If you want to read in an entire line, try bufio.Reader's ReadLine.

- Evan

Tobias Matt

unread,
Jul 28, 2011, 6:15:25 PM7/28/11
to golang-nuts
Thanks. That's what I searched.
Reply all
Reply to author
Forward
0 new messages