I am trying to write a function that reads a slice of integers, such as
"[1,5,3,2,0]", from a text file. Here is the code:
func readSlice(reader *os.File) []int {
slice := []int{}
_,err := fmt.Fscanf(reader, "[");
if (err != nil) {
panic("Slice should start with '['!")
}
var el int
for {
_,err := fmt.Fscanf(reader, "%d", &el);
if err != nil {
break;
}
slice = append(slice, el)
}
_,err = fmt.Fscanf(reader, "]");
if (err != nil) {
panic("Slice should end with ']'!")
}
return slice
}
Contrary to my expectations, when Fscanf encounters "]" instead of an
integer, it does not push "]" back (as fscanf() would have done in C), so
the program panics.
Is there an easy fix or work-around for this problem?
Thank you!
Meir