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

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

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

问题

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

例如:

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

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

[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 3 5 7 9 11]

答案1

得分: 1

我找到了答案:

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 GetInputSlice() []int {

	scanner := bufio.NewScanner(os.Stdin)
	scanner.Scan() // -------------------------------> was missing this before
	return numbers(scanner.Text())

}

func main() {
	fmt.Println("输入整数序列:")
	var fullslice []int
	fullslice = GetInputSlice()
	fmt.Println("输入整数序列:", fullslice)

}

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

英文:

i found my answer

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 GetInputSlice() []int {

	scanner := bufio.NewScanner(os.Stdin)
	scanner.Scan() // -------------------------------> was missing this before
	return numbers(scanner.Text())

}

func main() {
	fmt.Println("Enter sequence of Intergers :")
	var fullslice []int
	fullslice = GetInputSlice()
	fmt.Println("Enter sequence of Intergers :", fullslice)

}

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:

确定