donxbje866688 2017-04-24 23:33
浏览 48
已采纳

从stdin读取以空格分隔的整数到int slice中

I'm trying to read from stdin two lines of an unknown number of space-separated integers. I would like to store each lines ints into their own int slice.

For example, my input may look like this:

1 2 3
4 5 6

and I want to read this into two []int:

[1,2,3]
[4,5,6]

This is what I have so far. scanner.Scan() is giving me the line, but I'm not sure how to convert that into a []int:

package main
import (
    "fmt"
    "os"
    "bufio"
)

func main() {
    var firstLine []int
    var secondLine []int

    scanner := bufio.NewScanner(os.Stdin)
    for scanner.Scan() {
        t := scanner.Text()
    }
}
  • 写回答

4条回答 默认 最新

  • dongtai6741 2017-04-25 00:29
    关注

    For example,

    numbers.go:

    package main
    
    import (
        "bufio"
        "fmt"
        "os"
        "strconv"
        "strings"
    )
    
    func numbers(s string) []int {
        var n []int
        for _, f := range strings.Fields(s) {
            i, err := strconv.Atoi(f)
            if err == nil {
                n = append(n, i)
            }
        }
        return n
    }
    
    func main() {
        var firstLine, secondLine []int
        scanner := bufio.NewScanner(os.Stdin)
        for i := 1; i <= 2 && scanner.Scan(); i++ {
            switch i {
            case 1:
                firstLine = numbers(scanner.Text())
            case 2:
                secondLine = numbers(scanner.Text())
            }
        }
        fmt.Println(firstLine)
        fmt.Println(secondLine)
    }
    

    Output:

    $ go run numbers.go
    1 2 3
    4 5 6
    [1 2 3]
    [4 5 6]
    $
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?