英文:
GoLang fmt.Scan type error skip next fmt.Scan
问题
我是你的中文翻译助手,以下是翻译好的内容:
我是GoLang的初学者,这是一个来自教程的示例代码。
func main() {
for {
var name string
var email string
var userTickets uint
// 询问用户信息
fmt.Println("请输入您的姓名")
fmt.Scan(&name)
fmt.Println("请输入您的电子邮件")
fmt.Scan(&email)
// 询问用户票数
fmt.Println("请输入票数")
if _, err := fmt.Scanln(&userTickets); err != nil {
fmt.Println(err)
}
}
}
我发现了一个有趣的问题:
如果我在"请输入票数"中输入"-1",它会抛出一个错误,因为userTickets的类型是uint。由于这个错误,它还会在下一次循环中为"请输入您的姓名"添加一个换行符。
结果会像这样:
请输入您的姓名
Test
请输入您的电子邮件
Test
请输入票数
-1
expected integer
请输入您的姓名 <= 这个输入被跳过了
请输入您的电子邮件
所以我想知道为什么会发生这种情况?如何解决这个问题(不改变uint类型为int类型)?
英文:
Am a beginner of GoLang here is a sample code from a tutorial.
func main() {
for {
var name string
var email string
var userTickets uint
// ask user for info
fmt.Println("Input your Name please")
fmt.Scan(&name)
fmt.Println("Input your Email please")
fmt.Scan(&email)
// ask user for number of tickets
fmt.Println("Input number of ticket")
if _, err := fmt.Scanln(&userTickets); err != nil {
fmt.Println(err)
}
}
}
Here is an interesting thing I found:
if I entered "-1" in "Input number of ticket". It will throw an error since userTickets is uint. With that err it will also put an "enter/next line" for "Input your Name please" in the next loop.
The result would look like this
Input your Name please
Test
Input your Email please
Test
Input number of tickect
-1
expected integer
Input your Name please <= this input is skipped
Input your Email please
So just wondering why this heppened? How can I resolve that (without changing type from uint to int)?
答案1
得分: 4
只是想知道为什么会发生这种情况?
因为-1不能存储在uint类型中。
我如何解决这个问题(不改变uint类型为int类型)?
你无法解决这个问题。
(正确的做法是不使用fmt.Scan,而是始终将整行读入字符串,然后解析字符串。)
英文:
> So just wondering why this heppened?
Because -1 cannot be stored in an uint.
> How can I resolve that (without changing type from uint to int)?
You cannot.
(The right thing to do is not to use fmt.Scan but to always read whole lines into a string and parse the string.)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论