4

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.

5
  • I don't see anything wrong. Try just printing the whole array at once. Commented Aug 26, 2014 at 16:46
  • I can't reproduce that, what version of Go are You using? and what OS? Commented Aug 26, 2014 at 16:47
  • play.golang.org/p/gHBNoy_HGN works fine Commented Aug 26, 2014 at 16:52
  • @Exill: For the Go version and OS, post the output of the go version command. Commented Aug 26, 2014 at 17:10
  • I use Go version 1.3. and OS Windows + LiteIDE. Commented Aug 27, 2014 at 11:08

3 Answers 3

3
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)
 }
Sign up to request clarification or add additional context in comments.

1 Comment

please add some description - over code only answer
1

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.

Comments

0
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.