dongxibo2095 2016-09-19 03:47
浏览 453
已采纳

在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?

  • 写回答

2条回答 默认 最新

  • dpd2349 2016-09-19 04:51
    关注

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?