4

I am using a third party tool in Go with the help of exec.Command and that program will print out a large integer value which obviously is in string format. I having trouble converting that string to int (or more specifically uint64).

Details: (You can ignore what program it is etc. but after running it will return me a large integer)

cmd := exec.Command(app, arg0, arg1, arg3)
stdout, err := cmd.Output()
if err != nil {
    fmt.Println(err.Error())
    return
}
temp := string(stdout)

After I ran above, I am trying to parse it as below

myanswer, err = strconv.Atoi(temp)  //I know this is not for uint64 but I am first trying for int but I actually need uint64 conversion
if err != nil {
    fmt.Println(err)
    return
}

Problem here is that the stdout is appending \r\n to its output which AtoI is not able to parse and gives the error

strconv.Atoi: parsing "8101832828\r\n": invalid syntax

Can someone pls help me on how to convert this string output to a uint64 and also int format pls?

Innocentguy
  • 113
  • 1
  • 1
  • 6
  • This link helped me! Sorry for the dup question http://stackoverflow.com/questions/37757683/parsing-integer-from-exec-command-output – Innocentguy Apr 01 '17 at 05:28

1 Answers1

2

The output contains special characters. First, you need to strip any these characters (e.g. \n or \r).
You can use strings.TrimSpace.

Then to parse a string as an int64, you would use:

if i, err := strconv.ParseInt(s, 10, 64); err == nil {
    fmt.Printf("i=%d, type: %T\n", i, i)
}
Christian
  • 1,676
  • 13
  • 19
VonC
  • 1,262,500
  • 529
  • 4,410
  • 5,250