Exill
Exill

Reputation: 41

Go Lang Print Inputted Array

I am studying Go lang right now and I encountered a problem when trying to print inputted Array. My code is like this:

package main

import (
    "fmt"
)

func main() {
    var n int
    fmt.Scan(&n)
    set(n)
}

func set(n int) {
    a := make([]int, n)
    for i := 0; i < n; i++ {
        fmt.Scan(&a[i])
    }
    for y := 0; y < n; y++ {
        fmt.Println(a[y])
    }
    return
}

my problem is when Inputted a number as a size for the array, that number always get printed too. Like when I inputted 8 as the array size then followed by the array value for example 10 9 8 7 6 5 4 3 then I get the wrong output: 8 10 9 8 7 6 5 4.Iit should be 10 9 8 7 6 5 4 3.

Upvotes: 4

Views: 8519

Answers (3)

jinugeorge
jinugeorge

Reputation: 99

i:=0
var a[5] int
for(i<5){
fmt.Print("Enter Input")
var input int
fmt.Scanf("%d",&input)
a[i]=input
i+=1
}
fmt.Print(a)

This seems to work for me.Please refer.

Upvotes: 0

Faisal
Faisal

Reputation: 31

package main
import ("fmt")
func main() {
  var n int
  fmt.Scan(&n)
  set(n)
}

func set(n int) {
  a := make([]int, n)
  for i := 0; i < n; i++ {
      fmt.Scan(&a[i])
    }
  fmt.Println(a)
 }

Upvotes: 3

dyoo
dyoo

Reputation: 12023

Can not duplicate problem yet. For example:

package main

import (
    "bytes"
    "fmt"
    "io"
)

func main() {
    var n int
    sampleInput := bytes.NewBufferString("3 1 2 3")
    fmt.Fscan(sampleInput, &n)
    set(sampleInput, n)
}

func set(input io.Reader, n int) {
    a := make([]int, n)
    for i := 0; i < n; i++ {
        fmt.Fscan(input, &a[i])
    }
    for y := 0; y < n; y++ {
        fmt.Println(a[y])
    }
    return
}

is a variation of your program. It has the expected behavior: it prints the numbers 1 2 3 that it read into the slice.

Upvotes: 1

Related Questions