如何在 Go 中的 fmt.Scanf() 之后刷新 Stdin? [英] How to flush Stdin after fmt.Scanf() in Go?
问题描述
目前有一个问题困扰着我.当从用户那里获取输入时,我想使用一个循环来要求用户重试,直到他们输入有效的输入:
Here's an issue that's bedeviling me at the moment. When getting input from the user, I want to employ a loop to ask the user to retry until they enter valid input:
// user_input.go
package main
import (
"fmt"
)
func main() {
fmt.Println("Please enter an integer: ")
var userI int
for {
_, err := fmt.Scanf("%d", &userI)
if err == nil {
break
}
fmt.Println("Sorry, invalid input. Please enter an integer: ")
}
fmt.Println(userI)
}
运行上面的,如果用户输入有效,没问题:
Running the above, if the user enters valid input, no problem:
请输入一个整数:
3
3
退出代码 0,进程正常退出.
但是尝试输入一个字符串呢?
But try inputting a string instead?
请输入一个整数:什么?
抱歉,输入无效.请输入一个整数:
抱歉,输入无效.请输入一个整数:
对不起...
等等,它会一个字符一个字符地循环,直到字符串用完.即使输入单个字符循环两次,我也假设它解析换行符.
Etc, and it keeps looping character by character until the string is exhausted. Even inputting a single character loops twice, I assume as it parses the newline.
无论如何,一定有办法在 Go 中刷新 Stdin 吗?
Anyways, there must be a way to flush Stdin in Go?
附言如果没有这样的功能,您将如何解决它以提供等效的功能?我什至失败了...
P.S. In the absence of such a feature, how would you work around it to provide equivalent functionality? I've failed even at that...
推荐答案
我会在每次失败后通过阅读直到行尾来解决这个问题.这将清除文本的其余部分.
I would fix this by reading until the end of the line after each failure. This clears the rest of the text.
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
stdin := bufio.NewReader(os.Stdin)
fmt.Println("Please enter an integer: ")
var userI int
for {
_, err := fmt.Fscan(stdin, &userI)
if err == nil {
break
}
stdin.ReadString('\n')
fmt.Println("Sorry, invalid input. Please enter an integer: ")
}
fmt.Println(userI)
}
这篇关于如何在 Go 中的 fmt.Scanf() 之后刷新 Stdin?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!