简体   繁体   English

如何在golang中使用空格距离输入

[英]How to take input with whitespace distance in golang

I wanted to take some input from user based on white space in golang.我想根据 golang 中的空白从用户那里获取一些输入。 The current code is...目前的代码是...

fmt.Scanf("%d\n", &N)
var a [10]int
for n := 0; n < N; n++ {
    fmt.Scanf("%d\n", &a[n])
}

This code will let me take input in terminal like...这段代码将让我在终端中输入...

5
1
2
3
4
5

So, a[] = {1,2,3,4,5} But I would like to take input in terminal like...所以,a[] = {1,2,3,4,5} 但我想在终端中输入...

5
1 2 3 4 5

So, a[] = {1,2,3,4,5} So please help to find what should I change in the for-loop above.所以,a[] = {1,2,3,4,5} 所以请帮忙找出我应该在上面的 for 循环中改变什么。

You can try something like this.你可以尝试这样的事情。 This will read in the first number which is the size of the array you want to create, then the next line will be the items of length (n) in the array这将读入第一个数字,这是您要创建的数组的大小,然后下一行将是数组中长度为 (n) 的项目

import (
    "bufio"
    "fmt"
    "io"
    "os"
    "strconv"
    "strings"
)

func main() {
  reader := bufio.NewReaderSize(os.Stdin, 1024 * 1024)

  nTemp, err := strconv.ParseInt(readLine(reader), 10, 64)
  checkError(err)
  n := int32(nTemp)

  arrTemp := strings.Split(readLine(reader), " ")

  var arr []int32

  for i := 0; i < int(n); i++ {
      arrItemTemp, err := strconv.ParseInt(arrTemp[i], 10, 64)
      checkError(err)
      arrItem := int32(arrItemTemp)
      arr = append(arr, arrItem)
  }

  fmt.Printf("%#v, arr", arr)
}

So when I try with your given input eg:因此,当我尝试使用您给定的输入时,例如:

5
1 2 3 4 5

// I get the following:
[]int32{1, 2, 3, 4, 5}, arr

The question you have asked seems to be common in sites like Hackerrank in any of the featured questions.在任何特色问题中,您提出的问题似乎在Hackerrank等网站中很常见。

Thank you martinomburajr & Casey Flynn.谢谢 martinomburajr 和 Casey Flynn。

I went through your answers and I did my own trial-and-error.我浏览了您的答案,并进行了自己的反复试验。 And finally found the somultion.终于找到了somultion。

var N int
fmt.Scanf("%d\n", &N)
a := make([]int, N)
for n := range a {
    fmt.Scanf("%d", &a[n])
}
fmt.Scanf("\n")

And it is working fine for my requirement.它可以很好地满足我的要求。 Thank you so much for the help.非常感谢你的帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM