问题描述
从字符串解析为整数时有时会被解析为0(尽管不是0)时遇到问题.
I have a problem when parsing from a string to an integer that sometimes the string is being parsed to 0, despite not being 0.
示例:
我首先要做的是将一个字符串解析为三个不同的整数.我的代码如下:
What I would like to do first is parsing a string into three different integers. My code looks as follows:
package main
import (
"bufio"
"fmt"
"os"
"strconv"
"strings"
)
func main() {
reader := bufio.NewReader(os.Stdin)
line, _ := reader.ReadString('\n')
splitted := strings.Split(line, " ")
N, _ := strconv.ParseInt(splitted[0], 0, 64) //Works as intended
P, _ := strconv.ParseInt(splitted[1], 0, 64) //Works as intended
Q, _ := strconv.ParseInt(splitted[2], 0, 64) //Does not work as intended
fmt.Print(N, P, Q) //For testing the parsing
}
如果我输入字符串"5 25 125",则输出将以某种方式变为:5 25 0.
If I input the string: "5 25 125", the output somehow becomes:5 25 0.
这是问题所在,有时解析会将整数解析为字符串的内容,应该这样做.但是有时它会将整数解析为零.
This is the problem, sometimes the parsing parses the integer to the content of the string, which it should. But sometimes it parses the integer into a zero.
这是为什么?
推荐答案
所以splitted[2]
是125\n
,您应该检查strconv.ParseInt(splitted[2], 0, 64)
中的错误,而不是nil
,以便返回的值为0.
So splitted[2]
is 125\n
, you should check the error in strconv.ParseInt(splitted[2], 0, 64)
, it's not nil
so that the returned value is 0.
这篇关于解析的字符串有时变为0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!