How to read multiple Integer values from a single line of input in go?

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

How to read multiple Integer values from a single line of input in go?

问题

我正在编写一个程序,我希望允许用户在提示时输入多个整数。

例如:

输入多个整数:1 3 5 7 9 11

我希望将它们存储在一个切片中:

  1. [1 3 5 7 9 11]
英文:

I am working on a program and I want to allow a user to enter multiple integers when prompted.

For example:

Enter multiple integers: 1 3 5 7 9 11

i want it to be stored in a slice

  1. [1 3 5 7 9 11]

答案1

得分: 1

我找到了答案:

  1. package main
  2. import (
  3. "bufio"
  4. "fmt"
  5. "os"
  6. "strconv"
  7. "strings"
  8. )
  9. func numbers(s string) []int {
  10. var n []int
  11. for _, f := range strings.Fields(s) {
  12. i, err := strconv.Atoi(f)
  13. if err == nil {
  14. n = append(n, i)
  15. }
  16. }
  17. return n
  18. }
  19. func GetInputSlice() []int {
  20. scanner := bufio.NewScanner(os.Stdin)
  21. scanner.Scan() // -------------------------------> was missing this before
  22. return numbers(scanner.Text())
  23. }
  24. func main() {
  25. fmt.Println("输入整数序列:")
  26. var fullslice []int
  27. fullslice = GetInputSlice()
  28. fmt.Println("输入整数序列:", fullslice)
  29. }

请注意,我只是将代码部分翻译成了中文,其他部分保持不变。

英文:

i found my answer

  1. package main
  2. import (
  3. "bufio"
  4. "fmt"
  5. "os"
  6. "strconv"
  7. "strings"
  8. )
  9. func numbers(s string) []int {
  10. var n []int
  11. for _, f := range strings.Fields(s) {
  12. i, err := strconv.Atoi(f)
  13. if err == nil {
  14. n = append(n, i)
  15. }
  16. }
  17. return n
  18. }
  19. func GetInputSlice() []int {
  20. scanner := bufio.NewScanner(os.Stdin)
  21. scanner.Scan() // -------------------------------> was missing this before
  22. return numbers(scanner.Text())
  23. }
  24. func main() {
  25. fmt.Println("Enter sequence of Intergers :")
  26. var fullslice []int
  27. fullslice = GetInputSlice()
  28. fmt.Println("Enter sequence of Intergers :", fullslice)
  29. }

huangapple
  • 本文由 发表于 2022年3月14日 21:49:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/71468848.html
匿名

发表评论

匿名网友

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

确定