This question already has an answer here:
How am I goingt take an array as input in golang ?
func main() {
var inPut []float32
fmt.Printf("Input? ")
fmt.Scanf("%s", &inPut)
fmt.Println(inPut)
for _, value := range inPut {
fmt.Print(value)
}
}
I tried the code above and it doesn't give me the right answer, should I use another type of scanner ?
the input I want to take in is something like [3.2 -6.77 42 -0.9]
</div>
What you want to use are called Slices.
An array has a fixed size: [n]T
is an array of n
values of type T
.
A slice, on the other hand, is a dynamically-sized, and flexible way of representing an array: []T
is a slice with elements of type T
.
Slices are more common in the Go world.
package main
import "fmt"
func main() {
len := 0
fmt.Print("Enter the number of floats: ")
fmt.Scanln(&len)
input := make([]float64, len)
for i := 0; i < len; i++ {
fmt.Print("Enter a float: ")
fmt.Scanf("%f", &input[i])
}
fmt.Println(input)
}
Output:
// Enter the number of floats: 4
// Enter a float: 3.2
// Enter a float: -6.77
// Enter a float: 42
// Enter a float: -0.9
// [3.2 -6.77 42 -0.9]
I hope this helps!