Aditya Kurkure
Aditya Kurkure

Reputation: 422

Avoiding blank space as an input in go

I am new to golang and have switched from python. I am trying to scan an array and display it back to the user. However if there are any trailing spaces go will not wait for the user to type the next int (as it happens in c++) but will instead use zero.

func main() {
    var k int
    fmt.Scanf("%d", &k)
    for i:= 0 ; i< k ; i++{
        arr(5)
    }
}
func arr(l int){
    arr:= make([]int, l)
    for i := 0; i < l; i++ {
        fmt.Scanf("%d",&arr[i])
    }
    fmt.Println(arr)
}

This is my code so when I enter

1_

1_2_3_4_5_ where underscore represents a black space it will print out

[0 1 2 3 4]

The expected result is

[1 2 3 4 5]

Is there something wrong with my code? Or is this just how the Scanf() function works and if so should what should I use so that it works similar to the c++ scanf()? I tried to read about why this happens on my own and came across buffers but I didn't understand how that comes in the picture here.

Upvotes: 0

Views: 688

Answers (1)

Marc
Marc

Reputation: 21055

Your output is a result of ignoring errors returned by fmt.Scanf.

With the input you showed the first call to fmt.Scanf inside arr() will return: 0 and unexpected newline.

The first value is the number of items successfully scanned. The second is the error returned. Because there is an error, arr[0] is not assigned anything and remains at the default value of 0. Since you are ignoring the error, the program continues to arr[1] and will scan 1 from the next line.

The error comes from the fact that newlines in the input need to match newlines in the format string, per the fmt.Scanf docs.

To properly handle the first line, you should have something like the following:

func main() {
    var k int
    n, err := fmt.Scanf("%d\n", &k)
    if err != nil {
        panic(err)
    }
    if n != 1 {
        panic("expected one input")
    }
    for i:= 0 ; i< k ; i++{
        arr(5)
    }
}

You will similarly need to handle newlines in arr().


Two pieces of advice:

  • never ignore errors
  • read the documentation for the functions you use

Upvotes: 2

Related Questions