使用Golang从stdin扫描一行数字。

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

golang scan a line of numbers from sdin

问题

我正在尝试从标准输入中读取输入,并将其保存在一个整数列表中。目前我的代码如下:

nums := make([]int, 0)
var i int
for {
    _, err := fmt.Scan(&i)
    if err != nil {
        if err == io.EOF {
            break
        }
        log.Fatal(err)
    }
    nums = append(nums, i)
}

目前程序无法跳出循环。我在文档中找不到检查换行符的简单方法。我该如何做呢?

编辑:

由于我知道几乎肯定会有四个数字,我尝试了以下代码:

var i0, i1, i2, i3 int
fmt.Scanf("%d %d %d %d\n", &i0, &i1, &i2, &i3)

但这只会扫描第一个数字,然后退出程序。我不确定这是否是因为我使用的是z-shell。

编辑:

为了澄清,程序将暂停并要求用户输入由空格分隔并以换行符终止的n个数字的列表。这些数字应该存储在一个数组中。

英文:

I'm trying to read input from stdin like

3 2 1<ENTER>

and save it in a list of ints. At the moment my code looks like this:

nums = make([]int, 0)
var i int
for {
    _, err := fmt.Scan(&i)
    if err != nil {
        if err==io.EOF { break }
        log.Fatal(err)
    }
    nums = append(nums, i)
}

at the moment the program never leaves the for-loop. I can't find an easy way to check for a newline character in the documentation. how would i do this?

Edit:

Since I know that there will almost certainly be four numbers, I tried the following:

var i0,i1,i2,i3 int
fmt.Scanf("%d %d %d %d\n", &i0, &i1, &i2, &i3)

but this only scanned the first number and then exited the program. I'm not sure if that's because of the z-shell I'm using.

Edit:

To clarify, the program will pause and ask for the user to input a list of n numbers separated by spaces and terminated with a newline. these numbers should be stored in an array.

答案1

得分: 5

好的,以下是翻译好的代码部分:

in := bufio.NewReader(os.Stdin)
line, err := in.ReadString('\n')
if err != nil {
    log.Fatal(err)
}
strs := strings.Split(line[0:len(line)-1], " ")
nums := make([]int, len(strs))
for i, str := range strs {
    if nums[i], err = strconv.Atoi(str); err != nil {
        log.Fatal(err)
    }
}

这段代码看起来确实有点冗长,但它是有效的。

英文:

Ok, I decided to bring out the large bufio hammer and solve it like this:

in := bufio.NewReader(os.Stdin)
line, err := in.ReadString('\n')
if err != nil {
    log.Fatal(err)
}
strs := strings.Split(line[0:len(line)-1], " ")
nums := make([]int, len(strs))
for i, str := range strs {
    if nums[i], err = strconv.Atoi(str); err != nil {
        log.Fatal(err)
    }
}

It does seem like an awful lot of code, but it works.

答案2

得分: 2

看起来你想要翻译的内容是关于使用Go语言中的fmt.Fscanln函数的代码示例。以下是翻译好的内容:

似乎你想要使用https://golang.org/pkg/fmt/#Fscanln

类似于

ok := func(err error) { if err != nil { panic(err) } }

for {
  var i, j, k int
  _, err := fmt.Fscanln(io.Stdin, &i, &j, &k)
  ok(err)
  fmt.Println(i, j, k)
}
英文:

It seems that you want https://golang.org/pkg/fmt/#Fscanln

Something like

ok := func(err error) { if err != nil { panic(err) } }

for {
  var i, j, k int
  _, err := fmt.Fscanln(io.Stdin, &i, &j, &k)
  ok(err)
  fmt.Println(i, j, k)
}

答案3

得分: 1

我建议使用"bufio"包和"scan()"方法。
以下是我从"stdin"读取两行并将其存储到数组中的代码。
希望这对你有帮助。

package main

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

func ReadInput() []string {
	var lines []string
	scanner := bufio.NewScanner(os.Stdin)

	for scanner.Scan() {
		lines = append(lines, scanner.Text())
		if len(lines) == 2 {
			break
		}
	}

	if err := scanner.Err(); err != nil {
		fmt.Fprintln(os.Stderr, err)
	}

	return lines
}

func main() {
	lines := ReadInput()
	count, _ := strconv.Atoi(lines[0])
	num := strings.Fields(lines[1])

	if count != len(num) {
		os.Exit(0)
	}

	// 在这里做你想做的事情
}

将接受两行输入。第一行是计数,第二行是所有的数字。你可以根据需要修改相同的代码。

示例:

3
1 5 10
英文:

I will suggest to use "bufio" package with the "scan()" method.
Following is the code where I'm reading two lines from "stdin" and storing the lines into an array.
Hope this helps you.

package main

import (

    "fmt"
    "bufio"
    "os"
    "strconv"
    "strings"
)

func ReadInput() []string{

    var lines []string
	scanner := bufio.NewScanner(os.Stdin)

    for scanner.Scan() {
	    lines = append(lines, scanner.Text())
        //count, _ := strconv.Atoi(lines[0])
		if len(lines) == 2 { break }
    }
	if err := scanner.Err(); err != nil {
	fmt.Fprintln(os.Stderr, err)
	}
	return lines
}
  
func main(){

	lines	:= ReadInput()
	count ,_ := strconv.Atoi(lines[0])
	num := strings.Fields(lines[1])
	if count != len(num) { os.Exit(0) }
 // Do whatever you want here
}

Two lines will be accepted. First line will have a count. Second line will have all the numbers. You can modify the same code as per your requirement.

Example:

3
1 5 10 

huangapple
  • 本文由 发表于 2015年10月8日 21:40:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/33017547.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定