I haven’t used the Scanner
type, but Johan might have a good idea by suggesting that. It’s in the bufio
package, and you can read about it there.
If you want to use ReadByte()
or ReadBytes()
it may be more complicated. You will need to read the bytes into a slice, and then later convert that into a string, and then you can convert that to an integer with strconv.Atoi()
.
Here is some code that will do the operations I described. First, some declarations.
var intToAdd int
var byteSlice []byte
var i int
Now, to read the input,
byteSlice, _ = reader.ReadBytes('\n')
reads bytes from the input into byteSlice, including the newline.
if len(byteSlice) == 2 && byteSlice[0] == 'X' { os.Exit(0) }
exits if the 1st byte is an ‘X’. (To keep the example simple, I’m assuming there was no error and the 2nd byte is a ‘\n’.)
s := string(byteSlice[:len(byteSlice)-1])
convert the slice into a string. (Notice that I subtract 1 from the length to ignore the newline at the end, which would confuse strconv.Atoi())
intToAdd, _ = strconv.Atoi(s)
Convert the string into an integer.
if(i < 3) { userSlice[i] = intToAdd; i++ } else { userSlice = append(userSlice,intToAdd) }
I didn’t use append() for the first three because append() adds to the end of an existing slice. When you used make() to create the slice, the 3 elements were initialized to zero.
I checked to make sure all that worked by writing a program that solves the problem you were given. So if you want to try this method, it should work as I described. Or at least you can look it over and maybe learn from it.