Home > Backend Development > Golang > How to Handle Invalid Input and Flush Standard Input After `fmt.Scanf()` in Go?

How to Handle Invalid Input and Flush Standard Input After `fmt.Scanf()` in Go?

Susan Sarandon
Release: 2024-10-27 07:26:28
Original
355 people have browsed it

How to Handle Invalid Input and Flush Standard Input After `fmt.Scanf()` in Go?

Flushing Stdin After fmt.Scanf() in Go

Issue: When using fmt.Scanf() to obtain user input, it can become challenging to handle invalid input effectively. If a user enters non-numeric characters, the loop continues to iterate, creating an undesirable experience.

Resolution:

To resolve this issue, it is crucial to flush stdin (standard input) after each input request. By doing so, any remaining invalid characters in the input buffer are discarded, ensuring that the subsequent input request begins with a clean slate.

Solution Using fmt.Scanln:

The fmt.Scanln function can be utilized to read a string from stdin and automatically handle newline characters. By employing fmt.Scanln, the loop can be simplified without requiring explicit flushing of stdin:

<code class="go">package main

import (
    "fmt"
)

func main() {
    fmt.Println("Please enter an integer: ")

    // Read in an integer
    var userI int
    _, err := fmt.Scanln(&userI)
    if err != nil {
        fmt.Printf("Error: %s", err.Error())
        return
    }
    fmt.Println(userI)
}</code>
Copy after login

Alternative Solutions:

In the absence of a built-in stdin flushing function, alternative solutions can be employed:

  • Using io.Discard: The io.Discard value can be passed to fmt.Scanf() to discard invalid input.
  • Combining fmt.Scanf() and bufio: By combining fmt.Scanf() with the bufio package, the ReadString() function can be leveraged to read an entire line of input, discard invalid characters, and continue the loop.

Conclusion:

While there is no built-in stdin flushing function in Go, techniques like using fmt.Scanln or alternative solutions can effectively handle invalid input and maintain a user-friendly loop.

The above is the detailed content of How to Handle Invalid Input and Flush Standard Input After `fmt.Scanf()` 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