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]
    $
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
  • dongqun5769 2017-04-24 23:57
    关注

    So, this is what I ended up doing. There is likely a more idiomatic way of solving it, though.

    package main
    import (
        "fmt"
        "os"
        "bufio"
        "strings"
        "strconv"
    )
    
    func main() {
    
        scanner := bufio.NewScanner(os.Stdin)
    
        scanner.Scan()
        parts := strings.Split(scanner.Text(), " ")
        lineOne := createIntSlice(parts)
    
        scanner.Scan()
        parts = strings.Split(scanner.Text(), " ")
        lineTwo := createIntSlice(parts)
    
        fmt.Println(lineOne)
        fmt.Println(lineTwo)
    }
    
    func createIntSlice(nums []string) []int {
        var r []int
        for _, v := range nums {
            i, _ := strconv.Atoi(v)
            r = append(r, i)
        }
        return r
    }
    
    评论
  • douci1677 2017-04-25 14:54
    关注
    package main
    
    import (
        "bufio"
        "fmt"
        "os"
        "strings"
    )
    
    // You receive a string as parameter
    // List receives N As a string slice
    // Returns N as a string slice
    func number(n string) []string {
        list := strings.Fields(n)
    
        return list
    }
    
    func main() {
        scanner := bufio.NewScanner(os.Stdin) //Receiving user data ...
    
        list := make([][]string, 0) // Declare a slice to receive other slices inside it
    
        for scanner.Scan() { // Scrolls all typed data to true
    
            // If the user does not type anything, that is, if he presses Enter an interrupt will occur
            if scanner.Text() == "" {
                break
            } else {
                list = append(list, number(scanner.Text())) // Adding the slice inside list
            }
        }
    
        fmt.Println(list) // print list
    }
    

    All data is going and returning as string, but you can convert them to integers easily.

    评论
  • duanjie5570 2018-08-23 19:21
    关注

    If you are looking for code to read input to solve problems in hackathons, here is your best solution

    package main
    
    import (
        "bufio"
        "os"
        "fmt"
    )
    
    func main() {
    
        reader := bufio.NewReader(os.Stdin)
    
        a:= read(reader,100000)
    
        fmt.Println(a)
    }
    
    func read (reader *bufio.Reader, n int)([]uint32) {
    
        a := make([]uint32, n)
        for i:=0; i<n; i++ {
            fmt.Fscan(reader, &a[i])
        }
    
        return a
    }
    
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 网络打印机Ip地址自动获取出现问题
  • ¥15 求局部放电案例库,用于预测局部放电类型
  • ¥100 QT Open62541
  • ¥15 stata合并季度数据和日度数据
  • ¥15 谁能提供rabbitmq,erlang,socat压缩包,记住版本要对应
  • ¥15 Vue3 中使用 `vue-router` 只能跳转到主页面?
  • ¥15 用QT,进行QGIS二次开发,如何在添加栅格图层时,将黑白的矢量图渲染成彩色
  • ¥50 监控摄像头 乐橙和家亲版 保存sd卡的文件怎么打开?视频怎么播放?
  • ¥15 Python的Py-QT扩展库开发GUI
  • ¥60 提问一下周期性信信号的问题