从标准输入中读取以空格分隔的整数,并将其存入整数切片中。

huangapple go评论97阅读模式
英文:

Read space separated integers from stdin into int slice

问题

我正在尝试从标准输入读取两行未知数量的以空格分隔的整数。我想将每行的整数存储到它们各自的整数切片中。

例如,我的输入可能是这样的:

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()
    }
}
英文:

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

答案1

得分: 10

例如,

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]
$
英文:

For example,

numbers.go:

package main

import (
	&quot;bufio&quot;
	&quot;fmt&quot;
	&quot;os&quot;
	&quot;strconv&quot;
	&quot;strings&quot;
)

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 &lt;= 2 &amp;&amp; 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]
$

答案2

得分: 4

如果你正在寻找用于读取输入并解决黑客马拉松问题的代码,这是你最好的解决方案。

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
}

这段代码使用Go语言编写,用于从标准输入读取数据。它包含一个read函数,该函数接受一个bufio.Reader和一个整数n作为参数,并返回一个包含nuint32类型元素的切片。在main函数中,我们创建了一个bufio.Reader对象,并将其传递给read函数来读取输入数据。最后,我们打印出读取的数据。

希望对你有帮助!

英文:

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

package main

import (
	&quot;bufio&quot;
	&quot;os&quot;
	&quot;fmt&quot;
)

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&lt;n; i++ {
		fmt.Fscan(reader, &amp;a[i])
	}
	
	return a
}

答案3

得分: 2

这是我最终做的。虽然可能有更习惯用法的解决方法。

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
}
英文:

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

package main
import (
    &quot;fmt&quot;
    &quot;os&quot;
    &quot;bufio&quot;
    &quot;strings&quot;
    &quot;strconv&quot;
)

func main() {
        
    scanner := bufio.NewScanner(os.Stdin)
    
    scanner.Scan()
    parts := strings.Split(scanner.Text(), &quot; &quot;)
    lineOne := createIntSlice(parts)
    
    scanner.Scan()
    parts = strings.Split(scanner.Text(), &quot; &quot;)
    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
}

答案4

得分: 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

英文:

For another option, you can implement fmt.Scanner:

package main

import (
   &quot;bytes&quot;
   &quot;fmt&quot;
)

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 != &#39;\n&#39; })
   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, &amp;d)
      if err != nil { break }
      s.tok = append(s.tok, d)
   }
   return nil
}

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

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

答案5

得分: 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("输入由空格分隔的10个整数序列:")
	scanner.Scan()
	inputSequence = scanner.Text()
	convertedSliceOfIntegers = StringToIntSlice(inputSequence)
}
英文:

A simpler way to Handle taking space separated integers in a slice !!

func StringToIntSlice(inputSequence string) []int {
	var slicedIntegerSequence = []int{}
	var splittedSequence = strings.Split(inputSequence, &quot; &quot;)
	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(&quot;Enter a Sequence of 10 Integers separated by spaces:&quot;)
	scanner.Scan()
	inputSequence = scanner.Text()
	convertedSliceOfIntegers = StringToIntSlice(inputSequence)
}

答案6

得分: -1

package main

import (
	"bufio"
	"fmt"
	"os"
	"strings"
)

// 你接收一个字符串作为参数
// List接收一个字符串切片N
// 返回一个字符串切片N
func number(n string) []string {
	list := strings.Fields(n)

	return list
}

func main() {
	scanner := bufio.NewScanner(os.Stdin) // 接收用户数据...

	list := make([][]string, 0) // 声明一个切片来接收其中的其他切片

	for scanner.Scan() { // 滚动所有输入的数据直到为真

		// 如果用户没有输入任何内容,也就是按下回车键,将会中断
		if scanner.Text() == "" {
			break
		} else {
			list = append(list, number(scanner.Text())) // 将切片添加到list中
		}
	}

	fmt.Println(list) // 打印list
}

所有的数据都以字符串形式传递和返回但你可以很容易地将它们转换为整数
英文:
package main

import (
	&quot;bufio&quot;
	&quot;fmt&quot;
	&quot;os&quot;
	&quot;strings&quot;
)

// 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() == &quot;&quot; {
			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.

huangapple
  • 本文由 发表于 2017年4月25日 07:33:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/43599253.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定