Home >Backend Development >Golang >How to Flush Standard Input (Stdin) in Go When Dealing with Invalid Inputs?

How to Flush Standard Input (Stdin) in Go When Dealing with Invalid Inputs?

Linda Hamilton
Linda HamiltonOriginal
2024-10-29 02:32:30320browse

How to Flush Standard Input (Stdin) in Go When Dealing with Invalid Inputs?

Flushing Standard Input (Stdin) in Go

In Go, when using fmt.Scanf() to read user input, it's crucial to handle invalid inputs to prevent looping issues. One common challenge is the inability to clear the input buffer after an invalid entry, causing subsequent inputs to be parsed incorrectly. This can be resolved by flushing Stdin.

fmt.Scanln()

One method to address this issue is to use fmt.Scanln(), which reads a complete line from the input. It consumes the remaining input after the specified format specifier, eliminating the need for explicit looping.

<code class="go">func someFunc() {
    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>

Using io.Scanf()

Alternatively, io.Scanf() can be utilized to read a specific format from the input, even if it's incomplete. If the input doesn't match the format, the remaining characters are left in the input buffer. To clear the buffer after such an error, use:

<code class="go">reader.Reset(reader.Bytes())</code>

where reader is the io.Reader object.

Other Considerations

If no built-in function is suitable, consider using a custom function that continuously reads and discards input until a newline is reached. This approach ensures that all remaining input is cleared from the buffer.

Remember, proper handling of invalid inputs is essential for robust user interactions.

The above is the detailed content of How to Flush Standard Input (Stdin) in Go When Dealing with Invalid Inputs?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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