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

时间:2017-04-24 23:33:43

标签: go

我试图从stdin中读取两行未知数量的以空格分隔的整数。我想将每行ints存储到它们自己的int切片中。

例如,我的输入可能如下所示:

1 2 3
4 5 6

我希望将其读入两个[]int

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

这是我到目前为止所拥有的。 scanner.Scan()给了我一行,但我不确定如何将其转换为[]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()
    }
}

6 个答案:

答案 0 :(得分:4)

例如,

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)
}

输出:

$ go run numbers.go
1 2 3
4 5 6
[1 2 3]
[4 5 6]
$

答案 1 :(得分:1)

所以,这就是我最终要做的事情。但是,可能有一种更惯用的解决方法。

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
}

答案 2 :(得分:1)

如果您正在寻找代码以读取输入内容以解决黑客马拉松中的问题,这是您的最佳解决方案

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 :(得分:0)

对于另一种选择,您可以实现 fmt.Scanner

package main

import (
   "bytes"
   "fmt"
)

type slice struct {
   tok []int
}

func (s *slice) Scan(state fmt.ScanState, verb rune) error {
   tok, err := state.Token(false, func(r rune) bool { return r != '\n' })
   if err != nil { return err }
   if _, _, err := state.ReadRune(); err != nil {
      if len(tok) == 0 {
         panic(err)
      }
   }
   b := bytes.NewReader(tok)
   for {
      var d int
      _, err := fmt.Fscan(b, &d)
      if err != nil { break }
      s.tok = append(s.tok, d)
   }
   return nil
}

func main() {
   var s slice
   fmt.Scan(&s)
   fmt.Println(s.tok) // [1 2 3]
}

https://golang.org/pkg/fmt#Scanner

答案 4 :(得分:0)

一种更简单的方法来处理切片中以空格分隔的整数!!

func StringToIntSlice(inputSequence string) []int {
    var slicedIntegerSequence = []int{}
    var splittedSequence = strings.Split(inputSequence, " ")
    for _, value := range splittedSequence {
        intValue, _ := strconv.Atoi(value)
        slicedIntegerSequence = append(slicedIntegerSequence, intValue)
    }
    return slicedIntegerSequence
}


func main() {

    var inputSequence string
    var convertedSliceOfIntegers = []int{}
    scanner := bufio.NewScanner(os.Stdin)

    fmt.Println("Enter a Sequence of 10 Integers separated by spaces:")
    scanner.Scan()
    inputSequence = scanner.Text()
    convertedSliceOfIntegers = StringToIntSlice(inputSequence)
}

答案 5 :(得分:-1)

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
}

所有数据都以字符串形式返回并返回,但您可以轻松地将它们转换为整数。