I've only just started using go so sorry in advance if any of my questions are very obvious but I've spent a long time looking for answers online and couldn't find what I was looking for.
I want to read a line of space separated int values and store them into an array. The number of values will be known before they are input but I'm fairly sure there must be a more simple or neat way of writing it than this:
package main
import "fmt"
func main() {
var array[5] int
fmt.Scanf("%d %d %d %d %d", &array[0], &array[1], &array[2], &array[3], &array[4])
fmt.Printf("%v", array)
}
I also need to make it so that the number of values can be changed (to up to 50) and they should still be stored in the array. I wrote a simple function to make the scanf function read the right amount of numbers but without writing out each array element all the way out to &array[49] I couldn't find a work around. Is there an easier way of storing all the values without having a really long list of array locations?
package main
import "fmt"
func main() {
var length int
fmt.Scanf("%d", &length)
var array[50] int
fmt.Scanf(scanFormat(length), &array[0], &array[1], &array[2]) //etc.
fmt.Printf("%v", array)
}
func scanFormat (N int) string{
if N==0 {
return ""
}
return "%d "+scanFormat(N-1)
}
You can go for bufio.NewScanner
to scan the whole line. The default split function is ScanLines.
NewScanner returns a new Scanner to read from r. The split function defaults to ScanLines.
func (s *Scanner) Text() string
Text returns the most recent token generated by a call to Scan as a newly allocated string holding its bytes
Parse the string value one by one to convert the string into integer values, append the data to the slice of integers. Now process the data in the way you want.
package main
import (
"bufio"
"fmt"
"os"
"strconv"
"strings"
)
func main() {
data := make([]int, 0)
scanner := bufio.NewScanner(os.Stdin)
counter := 0
for scanner.Scan() {
output := strings.Split(scanner.Text(), " ")
for _, value := range output {
i, err := strconv.Atoi(value)
if err != nil {
fmt.Println(err)
}
data = append(data, i)
}
counter++
}
if err := scanner.Err(); err != nil {
fmt.Fprintln(os.Stdout, "reading standard input:", err)
}
fmt.Println("the data from terminal: ", data)
}