2017-11-04 95 views
0

我試圖在圍棋基礎添加計算器(這裏完整的小白),但每次我得到的0strconv.Atoi在Go(基本計算器)

這樣的輸出時間是代碼:

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) 

} 

回答

4

bufio.Reader.ReadString()返回數據,直到幷包括所述隔板。所以你的字符串實際上最終是"172312\n"strconv.Atoi()不喜歡那樣並返回0.它實際上返回一個錯誤,但你忽略它與_

你可以看到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) 
} 

您可以strings.Trim(number, "\n")修剪換行。