I'm trying to build a very basic console inputs for a program using a loop. However, when user inputs something else than an integer, the error message triggers as many times as there are characters in the input string (including newline).
I've tried Scan(), Scanln(), as well as bufio.NewReader() with string parsing, as well as using continue after Println(). All produce the same result.
var threads int
func main() {
fmt.Println("Enter number of threads:")
for {
_, err := fmt.Scanln(&threads)
if err != nil {
fmt.Println("Enter a valid number")
} else {
break
}
}
}
User inputs:
asd
Expected result:
Program: Enter a valid number
Actual result:
Program: Enter a valid number
Program: Enter a valid number
Program: Enter a valid number
Program: Enter a valid number