GoLang fmt.Scan 类型错误跳过下一个 fmt.Scan
GoLang fmt.Scan type error skip next fmt.Scan
我是 GoLang 的初学者,这里是教程中的示例代码。
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)
}
}
}
这是我发现的一件有趣的事:
如果我在“输入票号”中输入“-1”。它会抛出错误,因为 userTickets 是 uint。对于这个错误,它还会在下一个循环中为“请输入您的姓名”放置一个“enter/next 行”。
结果看起来像这样
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
所以只是想知道为什么会这样?我该如何解决(不将类型从 uint 更改为 int)?
So just wondering why this heppened?
因为-1不能存储在uint中。
How can I resolve that (without changing type from uint to int)?
你不能。
(正确的做法不是使用 fmt.Scan,而是始终将整行读入字符串并解析字符串。)
我是 GoLang 的初学者,这里是教程中的示例代码。
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)
}
}
}
这是我发现的一件有趣的事: 如果我在“输入票号”中输入“-1”。它会抛出错误,因为 userTickets 是 uint。对于这个错误,它还会在下一个循环中为“请输入您的姓名”放置一个“enter/next 行”。 结果看起来像这样
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
所以只是想知道为什么会这样?我该如何解决(不将类型从 uint 更改为 int)?
So just wondering why this heppened?
因为-1不能存储在uint中。
How can I resolve that (without changing type from uint to int)?
你不能。
(正确的做法不是使用 fmt.Scan,而是始终将整行读入字符串并解析字符串。)