strconv.Atoi in Go (Basic calculator)

醉酒当歌 提交于 2021-02-08 11:26:16

问题


I'm trying to make a basic adding calculator in Go (complete noob here), but every time I'm getting an output of 0.

This is the code:

package main

import (
    "fmt"
    "strconv"
    //"flag"
    "bufio"
    "os"
)

func main(){
     reader := bufio.NewReader(os.Stdin)
     fmt.Print("What's the first number you want to add?: ")
     firstnumber, _ := reader.ReadString('\n')
     fmt.Print("What's the second number you want to add?: ")
     secondnumber, _ := reader.ReadString('\n')
     ifirstnumber, _ := strconv.Atoi(firstnumber)
     isecondnumber, _ := strconv.Atoi(secondnumber)
     total := ifirstnumber + isecondnumber
     fmt.Println(total)

}

回答1:


bufio.Reader.ReadString() returns data up until and including the separator. So your string actually ends up being "172312\n". strconv.Atoi() doesn't like that and returns 0. It actually returns an error but you're ignoring it with _.

You can see what happens with this example:

package main

import (
    "fmt"
    "strconv"
)

func main(){
     ifirstnumber, err := strconv.Atoi("1337\n")
     isecondnumber, _ := strconv.Atoi("1337")
     fmt.Println(err)
     fmt.Println(ifirstnumber, isecondnumber)
}

You can trim the newlines with strings.Trim(number, "\n").



来源:https://stackoverflow.com/questions/47107014/strconv-atoi-in-go-basic-calculator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!