Home > Backend Development > Golang > Why Does fmt.Scanf() Cause an Infinite Loop with Invalid Input in Go?

Why Does fmt.Scanf() Cause an Infinite Loop with Invalid Input in Go?

Patricia Arquette
Release: 2024-10-27 04:23:30
Original
464 people have browsed it

Why Does fmt.Scanf() Cause an Infinite Loop with Invalid Input in Go?

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>
Copy after login

Additional Options

If fmt.Scanln() is not optimal, other options include:

  • Resetting the Stdin buffer: Use bufio.Reader.Reset() or bufio.NewReader() to clear the buffer.
  • Custom input validation: Create a loop that repeatedly reads and validates input until valid input is received.
  • Use a dedicated input library: Consider using a library such as bufio.Reader, which provides more control over input handling.

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template