gpt4 book ai didi

if-statement - if 语句总是被跳过

转载 作者:IT王子 更新时间:2023-10-29 02:31:03 25 4
gpt4 key购买 nike

我正在尝试制作一个基本的小银行程序来了解我对 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)
}
}
}

最佳答案

尝试使用 ReadLine() 方法而不是 ReadString()

医生说

ReadLine tries to return a single line, not including the end-of-line bytes.

ReadString reads until the first occurrence of delim in the input, returning a string containing the data up to and including the delimiter

这里是更新后的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")
}

关于if-statement - if 语句总是被跳过,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54423896/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com