search
  • Sign In
  • Sign Up
Password reset successful

Follow the proiects vou are interested in andi aet the latestnews about them taster

0 answers
Q&A How to flush Stdin after fmt.Scanf() in Go?
How to flush Stdin after fmt.Scanf() in Go?
P粉769045426 2025-12-28 07:43:18 Views 117

0

Here's an issue that's bedeviling me at the moment. When getting input from the user, I want to employ a loop to ask the user to retry until they enter valid input:

// user_input.go
package main

import (
    "fmt"
)

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

    var userI int

    for {
        _, err := fmt.Scanf("%d", &userI)
        if err == nil {
            break
        }
        fmt.Println("Sorry, invalid input. Please enter an integer: ")
    }

    fmt.Println(userI)    
}

Running the above, if the user enters valid input, no problem:

Please enter an integer: 

3

3

exit code 0, process exited normally.

But try inputting a string instead?

Please enter an integer: 
what?
Sorry, invalid input. Please enter an integer:

Sorry, invalid input. Please enter an integer:

Sorry...

Etc, and it keeps looping character by character until the string is exhausted. Even inputting a single character loops twice, I assume as it parses the newline.

Anyways, there must be a way to flush Stdin in Go?

P.S. In the absence of such a feature, how would you work around it to provide equivalent functionality? I've failed even at that...

Your Answer
submit

0 answers

Popular tool

vc9-vc14 (32+64 bit) runtime library collection (link below)

vc9-vc14 (32+64 bit) runtime library collection (link below)

Download the collection of runtime libraries required for phpStudy installation

VC9 32-bit

VC9 32-bit

VC9 32-bit phpstudy integrated installation environment runtime library

PHP programmer toolbox full version

PHP programmer toolbox full version

Programmer Toolbox v1.0 PHP Integrated Environment

VC11 32-bit

VC11 32-bit

VC11 32-bit phpstudy integrated installation environment runtime library

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use