Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fmt.Scanln expected newline error

Tags:

input

go

I'm trying to learn Go, but stuck with this one: http://ideone.com/hbCamr or http://ideone.com/OvRw7t

package main
import "fmt"

func main(){
  var i int
  var f float64
  var s string

  _, err := fmt.Scan(&i)
  if err == nil {
    fmt.Println("read 1 integer: ",i)
  } else {
    fmt.Println("Error: ",err)
  }

  _, err = fmt.Scan(&f)
  if err == nil {
    fmt.Println("read 1 float64: ",f)
  } else {
    fmt.Println("Error: ",err)
  }
  _, err = fmt.Scan(&s)
  if err == nil {
    fmt.Println("read 1 string: ",s)
  } else {
    fmt.Println("Error: ",err)
  }

  _, err = fmt.Scanln(&s)
  if err == nil {
    fmt.Println("read 1 line: ",s)
  } else {
    fmt.Println("Error: ",err)
  }
}

for this input:

123
123.456
everybody loves ice cream

the output was:

read 1 integer:  123
read 1 float64:  123.456
read 1 string:  everybody
Error:  Scan: expected newline

is this the expected behavior? why doesn't it work like C++ getline? http://ideone.com/Wx8z5o

like image 828
Kokizzu Avatar asked Dec 11 '22 05:12

Kokizzu


1 Answers

The answer is in the documentation of Scanln:

Scanln is similar to Scan, but stops scanning at a newline and after the final item there must be a newline or EOF.

Scan behaves as documented as well:

Scan scans text read from standard input, storing successive space-separated values into successive arguments. Newlines count as space. It returns the number of items successfully scanned. If that is less than the number of arguments, err will report why.

To conclude: Scan puts each word (a string separated by space) into a corresponding argument, treating newlines as space. Scanln does the same but treats newlines as a stop character, not parsing any further after that.

In case you want to read a line (\n at the end) use bufio.Reader and its ReadString method:

line, err := buffer.ReadString('\n')
like image 161
nemo Avatar answered Dec 29 '22 01:12

nemo