英文:
Issue with parsing Go Command().Output()
问题
我正在使用Go语言中的exec.Command和第三方工具,该程序将输出一个大整数值,显然是以字符串格式表示的。我在将该字符串转换为int(或更具体地说是uint64)方面遇到了问题。
详情:
(您可以忽略程序是什么等等,但运行后它将返回一个大整数)
cmd := exec.Command(app, arg0, arg1, arg3)
stdout, err := cmd.Output()
if err != nil {
fmt.Println(err.Error())
return
}
temp := string(stdout)
在上述代码运行后,我尝试进行以下解析:
myanswer, err = strconv.Atoi(temp) //我知道这不是用于uint64的,但我首先尝试int,但实际上我需要uint64的转换
if err != nil {
fmt.Println(err)
return
}
问题在于stdout的输出附加了\r\n
,导致AtoI无法解析并报错:
strconv.Atoi: parsing "8101832828\r\n": invalid syntax
请问有人可以帮助我将此字符串输出转换为uint64和int格式吗?
英文:
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?
答案1
得分: 2
输出包含特殊字符。首先,你需要去除这些字符(例如\n
或\r
)。你可以使用strings.TrimSpace
。
然后,要将字符串解析为int64
,你可以使用以下方法:
if i, err := strconv.ParseInt(s, 10, 64); err == nil {
fmt.Printf("i=%d, type: %T\n", i, i)
}
英文:
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)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论