1 回答
TA贡献1829条经验 获得超7个赞
如果可以,将responsefrom的类型切换为int,然后使用包(例如)string解析输入字符串。我怀疑正在尝试将您输入的每个字符作为单独的 int 读取,每次都失败,并且每次都运行循环,直到所有字符都被消耗完。strconvstrconv.Atoi()Scan
例如
for {
var response string
fmt.Printf("How many %v would you like to buy? ", product.Name)
_, err := fmt.Scanln(&response)
if err != nil { // probably don't need to check err from Scan()
fmt.Println(err)
continue
}
num, err := strconv.Atoi(response)
if err != nil {
fmt.Println("Enter an integer.")
continue
}
if ok, err := validResponse(num); ok && err==nil {
break
} else {
fmt.Println(err)
continue
}
}
- 1 回答
- 0 关注
- 67 浏览
添加回答
举报