Search code examples
gocalculatorstrconv

strconv.Atoi in Go (Basic calculator)


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)

}

Solution

  • 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").