kosta
kosta

Reputation: 4740

Read a set of integers separated by space in Golang

I want to read a set of integer values from stdin and put it into integer slice. What is the fastest way to do that without using for loop.

e.g.

Enter the number of integers
3
Enter the integers
23 45 66

How can I put these values in an integer slice?

Upvotes: 6

Views: 6547

Answers (2)

Muhammad Soliman
Muhammad Soliman

Reputation: 23756

Simpler solution using loop without the need for using recursion function:

    var n int

    if _, err := fmt.Scan(&n); err != nil {
        panic(err)
    }

    arr := make([]int, n)

    for i := 0;i<n;i++{

        if _, err := fmt.Scan(&arr[i]); err != nil {
            panic(err)
        }
    }

    fmt.Println(arr)

Upvotes: 5

user6169399
user6169399

Reputation:

Anyway there is a loop, Here without for and goto loop ( try it on The Go Playground):

package main

import "fmt"

func main() {
    fmt.Println(`Enter the number of integers`)
    var n int
    if m, err := Scan(&n); m != 1 {
        panic(err)
    }
    fmt.Println(`Enter the integers`)
    all := make([]int, n)
    ReadN(all, 0, n)
    fmt.Println(all)
}

func ReadN(all []int, i, n int) {
    if n == 0 {
        return
    }
    if m, err := Scan(&all[i]); m != 1 {
        panic(err)
    }
    ReadN(all, i+1, n-1)
}

func Scan(a *int) (int, error) {
    return fmt.Scan(a)
}

io:

Enter the number of integers
3
Enter the integers
10 20 30
[10 20 30]

For faster input scanning rewrite:

func Scan(a *int) (int, error) {
    return fmt.Scan(a)
}

using:
Faster input scanning

Upvotes: 7

Related Questions