如果语句总是被跳过

时间:2019-01-29 15:02:35

标签: if-statement go input

我正在尝试编写一个基本的小型银行计划,以使自己对Go有所了解。我运行该程序,当我为两个if语句输入答案时,该程序就会继续运行。有解决方案吗?

这是我的代码:

package main
import (
    "bufio"
    "fmt"
    "os"
    "strconv"
    "strings"
)

func main() {
    reader := bufio.NewReader(os.Stdin)
    fmt.Print("Enter your name: ")
    name, _ := reader.ReadString('\n')
    fmt.Print("Hello ", name)
    balance := 0
    fmt.Print("Do you want to deposite? (y/n) ")
    doDeposite, _ := reader.ReadString('\n')
    if strings.TrimRight(doDeposite, "\n") == "y" {
        fmt.Print("How much would you like to deposite? ")
        depositeAmount, _ := reader.ReadString('\n')
        da, _ := strconv.Atoi(depositeAmount)
        balance += balance + da
        fmt.Print("Your balance is ", balance)
    } else {
        fmt.Print("Would you like to withdraw?(y/n) ")
        doWithdraw, _ := reader.ReadString('\n')
        if strings.TrimRight(doWithdraw, "\n") == "y" {
            fmt.Print("How much would you like to withdraw? ")
            withdrawAmount, _ := reader.ReadString('\n')
            wa, _ := strconv.Atoi(withdrawAmount)
            balance += balance + wa
            fmt.Print("Your balance is ", balance)
        }
    }
}

1 个答案:

答案 0 :(得分:3)

尝试使用ReadLine()方法代替ReadString()

医生说

  

ReadLine尝试返回单行,不包括行尾字节。

     

ReadString读取直到输入中第一次出现delim为止,并返回一个字符串,其中包含直到包括定界符的数据

以下是更新的deposit代码供参考:

[...]
    fmt.Print("How much would you like to deposit? ")
    depositAmount, _, err := reader.ReadLine()
    if err != nil {
      fmt.Printf("ReadLine() error: '%s'", err)
    }
    da, err := strconv.Atoi(string(depositAmount))
    if err != nil {
      fmt.Printf("strconv error: '%s'", err)
    }
    balance += balance + da
    fmt.Print("Your balance is ", balance)
[...]

或者,您可以根据要执行代码的操作系统进行修整。

if runtime.GOOS == "windows" {
  input = strings.TrimRight(input, "\r\n")
} else {
  input = strings.TrimRight(input, "\n")
}