doubi5520 2017-04-09 12:44
浏览 54

解析的字符串有时变为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('
')

    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条回答 默认 最新

  • dongsong4418 2017-04-09 13:02
    关注

    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 , you should check the error in strconv.ParseInt(splitted[2], 0, 64), it's not nil so that the returned value is 0.

    评论

报告相同问题?

悬赏问题

  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?