Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

golang scan a line of numbers from sdin

Tags:

go

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.

like image 524
ehrt1974 Avatar asked Feb 09 '23 20:02

ehrt1974


2 Answers

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.

like image 113
ehrt1974 Avatar answered Feb 11 '23 22:02

ehrt1974


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)
}
like image 20
nes1983 Avatar answered Feb 11 '23 21:02

nes1983