dongxibo2095
2016-09-19 03:47 阅读 237
已采纳

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

    点赞 评论 复制链接分享
  • duanhe1976 duanhe1976 2017-11-09 19:58

    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)
    
    点赞 评论 复制链接分享

相关推荐