Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

golang accepting input with spaces

Tags:

input

go

space

I'm just starting with GO and I understand that SCANF uses spaces as a separator in GO.

fmt.Scanf("%s",&input)

I cant really find a way to accepts inputs that contain spaces as valid characters.

like image 882
av192 Avatar asked Dec 11 '14 02:12

av192


2 Answers

you can use bufio.Reader and os.Stdin:

import(
  "bufio"
  "os"
)

in := bufio.NewReader(os.Stdin)

line, err := in.ReadString('\n')
like image 162
rchlin Avatar answered Nov 08 '22 17:11

rchlin


Similar to @chlin's answer, use bufio to capture whole lines.

The fmt Scan methods store each space separated value into a successive arguments. Three arguments on stdin would require something like:

package main

import "fmt"

func main() {
    var day, year int
    var month string
    fmt.Scanf("%d %s %d", &day, &month, &year)
    fmt.Printf("captured: %d %s %d\n", day, month, year)
}

If you don't know the full format of what you will be reading and just want the line, use bufio:

package main

import (
  "bufio"
  "os"
)

func main(){
    scanner := bufio.NewScanner(os.Stdin)
    scanner.Scan() // use `for scanner.Scan()` to keep reading
    line := scanner.Text()
    fmt.Println("captured:",line)
}
like image 28
sethammons Avatar answered Nov 08 '22 17:11

sethammons