Home >Backend Development >Golang >How to Handle Invalid User Input in Go: Flushing Stdin and Alternatives
Understanding Input Consumption in Go: Flushing and Alternatives
When interacting with users through the terminal, handling invalid input can be challenging. In Go, using fmt.Scanf() to read input may encounter issues when users enter non-integer values. This is because fmt.Scanf() doesn't consume the entire line, leaving residual characters that may interfere with subsequent input.
To address this issue, one option is to explicitly flush the input buffer after an invalid entry. However, Go does not provide a direct method for flushing Stdin.
Alternative Approaches:
<code class="go">fmt.Println("Please enter an integer:") var userI int _, err := fmt.Scanln(&userI) if err != nil { fmt.Println("Sorry, invalid input. Please try again:") }</code>
<code class="go">func GetUserInputInt() int { var userI int for { fmt.Println("Please enter an integer:") _, err := fmt.Scanf("%d", &userI) if err == nil { return userI } fmt.Println("Sorry, invalid input. Please try again:") fmt.Scanln() // Discard invalid input } }</code>
The above is the detailed content of How to Handle Invalid User Input in Go: Flushing Stdin and Alternatives. For more information, please follow other related articles on the PHP Chinese website!