How to Handle Invalid Input in Go's fmt.Scanf
For those encountering issues with invalid input while using fmt.Scanf(), it's essential to understand why the program goes into an infinite loop when a string is entered instead of an integer.
In Go, fmt.Scanf() parses the input stream for a specific format specifier (e.g., "%d" for a decimal integer). Invalid input, such as a string, causes an error, but the input remains in the Stdin buffer. Consequently, subsequent calls to fmt.Scanf() continue to process the same invalid input, resulting in an infinite loop.
Solution Using fmt.Scanln
An alternative approach is to use fmt.Scanln(), which behaves differently. It reads and consumes the entire line of input, including any invalid characters. This can be implemented as follows:
<code class="go">fmt.Printf("Please enter an integer: ") // Read in an integer var i int _, err := fmt.Scanln(&i) if err != nil { fmt.Printf("Error: %s", err.Error()) // If int read fails, read as string and forget var discard string fmt.Scanln(&discard) return } fmt.Printf("Input contained %d", i)</code>
Additional Options
If fmt.Scanln() is not optimal, other options include:
The above is the detailed content of Why Does fmt.Scanf() Cause an Infinite Loop with Invalid Input in Go?. For more information, please follow other related articles on the PHP Chinese website!