How to scan a string?

5,964 views
Skip to first unread message

Lambda

unread,
Jun 14, 2010, 9:34:38 PM6/14/10
to golang-nuts
I'm trying to scan a string from stdin, the code is very simple:

package main

import (
"fmt"
)

func main() {
var line string
n, err := fmt.Scanln(&line)
fmt.Println(n, err, line)
}

But when I run it:

200:clrs3 stephen$ ./6.out
hello, world!
1 Scan: expected newline hello,
200:clrs3 stephen$ orld!
-bash: orld!: command not found

It looks like Scanln stops at the first space.
The doc says: 'Scanln is similar to Scan, but stops scanning at a
newline and after the final item there must be a newline or EOF.'
What's wrong with the code?

Steven

unread,
Jun 14, 2010, 10:59:06 PM6/14/10
to Lambda, golang-nuts
The problem with you're code is that you have only provided space for 1 word, and there are two. Scanln still separates items by spaces, but rather than just filling up whatever you give it, it tries to take everything on the line. If you don't have enough variables for the whole line, then you will get an error, because it will expect a newline after the final item it can give you, and there isn't one.

Scan and scanln are for parsing and stuff like that, so just getting a single line of text from stdin would defeat the purpose. If that's what you want to do, you should use a bufio.Reader and os.Stdin:

import ("bufio", "os")
...
in := bufio.NewReader(os.Stdin)
line, err := in.ReadString('\n')

Rob 'Commander' Pike

unread,
Jun 15, 2010, 12:36:45 AM6/15/10
to Lambda, golang-nuts

But you didn't read the definition of Scan:

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

-rob

Lambda

unread,
Jun 15, 2010, 11:14:23 PM6/15/10
to golang-nuts
> But you didn't read the definition of Scan:
>
>         Scan scans text read from standard input, storing successive
>         space-separated values into successive arguments.
>
> -rob

Thanks. Then if I want to scan a space-separated line, but I don't
know how many entries are there beforehand, may I use scan anymore?
All I want to do is something like 'line = map(int,
raw_input().split())' in Python.

Steven

unread,
Jun 15, 2010, 11:40:53 PM6/15/10
to Lambda, golang-nuts
Once you have the string from the bufio method, you can then use strings.Fields to split at white space, or strings.Split to split at a delimiter of your choice.
Reply all
Reply to author
Forward
0 new messages