解析的字符串有时会变成0

huangapple go评论72阅读模式
英文:

Parsed strings sometimes becomes 0

问题

我在将字符串解析为整数时遇到了一个问题,有时候字符串被解析为0,尽管它不是0。

示例:

首先,我想将一个字符串解析为三个不同的整数。我的代码如下:

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) //按预期工作
    P, _ := strconv.ParseInt(splitted[1], 0, 64) //按预期工作
    Q, _ := strconv.ParseInt(splitted[2], 0, 64) //不按预期工作

    fmt.Print(N, P, Q)  //用于测试解析结果
}

如果我输入字符串:"5 25 125",输出结果却变成了:
5 25 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.

Example:

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

}

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.

Why is this?

答案1

得分: 3

ReadString函数会读取输入直到遇到第一个分隔符(delim),并返回包含分隔符在内的数据字符串。

所以splitted[2]的值是125\n,你应该检查strconv.ParseInt(splitted[2], 0, 64)中的错误,如果不是nil,那么返回的值就是0。

英文:

> ReadString reads
> until the first occurrence of delim in the input, returning a string
> containing the data up to and including the delimiter.

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.

huangapple
  • 本文由 发表于 2017年4月9日 20:44:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/43306821.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定