golang从sdin扫描一行数字 [英] golang scan a line of numbers from sdin

查看:127
本文介绍了golang从sdin扫描一行数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图从stdin读取输入,例如

  3 2 1< ENTER> 

并将其保存在整数列表中。目前我的代码如下所示:

$ $ p $ $ $ $ $ $ $
for {
_,err:= fmt.Scan(& i)
if err!= nil {
if err == io.EOF {break}
log.Fatal(err)
}
nums = append(nums,i)
}

程序从不离开for循环。我找不到在文档中检查换行符的简单方法。我怎么会这样做?



编辑:

因为我知道几乎肯定会有四个数字,我尝试了以下方法:

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

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



编辑:



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

解决方案

好的,我决定带出大型bufio锤子并像这样解决:

  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:=范围strs {
如果nums [i],err = strconv .Atoi(STR); err!= nil {
log.Fatal(err)
}
}

它看起来好像很多代码,但它有效。


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.

解决方案

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.

这篇关于golang从sdin扫描一行数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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