I'm currently trying to run a command from inside my Go program and parse an integer from the response. The command returns output like this:
6
fyb_src/ex1.fyb (1) wins!
Splitting the lines and removing the whitespace with strings.Split
and strings.TrimSpaces
works fine. However, while trying to parse the number into an integer I get the following error:
panic: strconv.ParseInt: parsing "0 1 2 3 4 5 6": invalid syntax
But printing the string I'm trying to parse to the terminal yields the following result:
6
I'm not really sure where to go from here. The number clearly looks like an integer to me. The error message isn't useful either (at least for me). Does anyone have an idea?
EDIT: The code I'm running
out, _ := exec.Command(pwd+"/osx_fukyobrane_amd64", "fyb_src/"+filename, "fyb_src/salty.fyb", "t").CombinedOutput()
parts := strings.Split(string(out), "
")
fmt.Println(parts[0])
rounds, err := strconv.Atoi(strings.TrimSpace(parts[0]))
if err != nil {
panic(err.Error())
}
It would appear that your problem is that parts[0]
contains the string "0 1 2 3 4 5 6"
instead of a number.
The strconv.Atoi function is looking for just one number to parse - I assume you are trying to get that first "0" in this case. If so, the problem is that this code: strings.Split(string(out), " ")
is only looking for " " not "", which is apparently what is being returned from osx_fukyobrane_amd64
.
One solution would be to instead split the lines like this:
regexp.MustCompile(`[
]+`).Split(parts[0], -1)
That will collapse multiple lines together into one and treat , , and (or other weird combinations) as valid line breaks.
It looks like there might be some additional escaped data on that line. Try splitting by space and using that.
out, _ := exec.Command(pwd+"/osx_fukyobrane_amd64", "fyb_src/"+filename, "fyb_src/salty.fyb", "t").CombinedOutput()
parts := strings.Split(string(out), "
")
parts = strings.Split(parts, " ")
fmt.Println(parts[0])
rounds, err := strconv.Atoi(strings.TrimSpace(parts[0]))
if err != nil {
panic(err.Error())
}
Use strings.Fields
instead of Split
, it automagically handle and
.
This is also much faster than using regexp, which is considerably slow in Go, although it is getting improved.
func splitAndTrim(line string) []string {
out := strings.Fields(line)
for i, s := range out {
out[i] = strings.TrimSpace(s)
}
return out
}