英文:
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)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论