在Golang中阅读由空间分隔的一组整数 [英] Read a set of integers separated by space in Golang

查看:86
本文介绍了在Golang中阅读由空间分隔的一组整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从标准输入读取一组整数值并将其放入整数片。 循环

例如

 输入整数数量
3
输入整数
23 45 66



如何将这些值放在整数切片中?

解决方案

无论如何有一个循环,这里没有用于 goto 循环(在 Go Go Playground ):


 包主
$ b导入fmt

func main(){
fmt.Println(`输入整数数量`)
var n int
if m,err:= Scan(& n); m!= 1 {
panic(err)
}
fmt.Println(`输入整数`)
all:= make([] int,n)
ReadN(all,0,n)
fmt.Println(全部)
}

func ReadN(全部[] int,i,n int){
如果n == 0 {
返回
}
if m,err:= Scan(& all [i]); m!= 1 {
panic(err)
}
ReadN(all,i + 1,n-1)
}

func扫描a * int)(int,error){
return fmt.Scan(a)
}



io:

 输入整数数量
3
输入整数
10 20 30
[10 20 30]






更快的输入扫描重写:

  func扫描(a * int)(int,error){
返回fmt.Scan(a)
}

使用:

更快的输入扫描


I want to read a set of integer values from stdin and put it into integer slice. What is the fastest way to do that without using for loop.

e.g.

Enter the number of integers
3
Enter the integers
23 45 66

How can I put these values in an integer slice?

解决方案

Anyway there is a loop, Here without for and goto loop ( try it on The Go Playground):

package main

import "fmt"

func main() {
    fmt.Println(`Enter the number of integers`)
    var n int
    if m, err := Scan(&n); m != 1 {
        panic(err)
    }
    fmt.Println(`Enter the integers`)
    all := make([]int, n)
    ReadN(all, 0, n)
    fmt.Println(all)
}

func ReadN(all []int, i, n int) {
    if n == 0 {
        return
    }
    if m, err := Scan(&all[i]); m != 1 {
        panic(err)
    }
    ReadN(all, i+1, n-1)
}

func Scan(a *int) (int, error) {
    return fmt.Scan(a)
}

io:

Enter the number of integers
3
Enter the integers
10 20 30
[10 20 30]


For faster input scanning rewrite:

func Scan(a *int) (int, error) {
    return fmt.Scan(a)
}

using:
Faster input scanning

这篇关于在Golang中阅读由空间分隔的一组整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆