如何使用fmt.Sscan解析整数到数组中? [英] How to use fmt.Sscan to parse integers into an array?
问题描述
我试图从字符串中扫描一个整数列表到一个数组中(或者一个切片) package main
$ b importfmt
func main(){
var nums [5] int
n,_:= fmt.Sscan( 1 2 3 4 5,& nums)//不起作用
fmt.Println(nums)
}
为了达到这个目的,我需要将第二个参数传递给 Sscan
我知道我可以传递 nums [0],nums [1] ...
等,但是我'd更喜欢一个参数。
我不认为这是一个方便的单线程。作为 Sscan
需要 ...接口{}
,您还需要传递一些接口,数组first:
func main(){
var nums [5] int
//转换为接口
xnums:= make([] interface {},len(nums))
for n:=范围nums {
xnums [n] =& nums [n ]
}
n,err:= fmt.Sscan(1 2 3 4 5,xnums ...)
if err!= nil {
fmt .Printf(field%d:%s \ n,n + 1,err)
}
fmt.Println(nums)
}
http ://play.golang.org/p/1X28J7JJwl
显然你可以在你的界面数组中混合不同的类型,所以它会使扫描更多复杂的字符串更容对于简单的空间限制整数,你可能会更好地使用 strings.Split
或 bufio.Scanner
以及 strconv.Atoi
。
I'm trying to scan a list of integers from a string into an array (or alternatively, a slice)
package main
import "fmt"
func main() {
var nums [5]int
n, _ := fmt.Sscan("1 2 3 4 5", &nums) // doesn't work
fmt.Println(nums)
}
What do I need to pass as second argument to Sscan
in order for this to work?
I know I could pass nums[0], nums[1] ...
etc., but I'd prefer a single argument.
I don't think this is possible as a convenient one-liner. As Sscan
takes ...interface{}
, you would need to pass slice of interfaces as well, hence converting your array first:
func main() {
var nums [5]int
// Convert to interfaces
xnums := make([]interface{}, len(nums))
for n := range nums {
xnums[n] = &nums[n]
}
n, err := fmt.Sscan("1 2 3 4 5", xnums...)
if err != nil {
fmt.Printf("field %d: %s\n", n+1, err)
}
fmt.Println(nums)
}
http://play.golang.org/p/1X28J7JJwl
Obviously you could mix different types in your interface array, so it would make the scanning of more complex string easier. For simply space-limited integers, you might be better using strings.Split
or bufio.Scanner
along with strconv.Atoi
.
这篇关于如何使用fmt.Sscan解析整数到数组中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!