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)
}
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:
You can trim the newlines with
strings.Trim(number, "\n").