解析的字符串有时变为0 [英] Parsed strings sometimes becomes 0

查看:87
本文介绍了解析的字符串有时变为0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从字符串解析为整数时有时会被解析为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.

这是为什么?

推荐答案

ReadString 读取 直到输入中第一次出现delim,然后返回一个字符串 包含直到定界符并包括定界符的数据.

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

所以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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆