I'm working through the Coursera Go course ... it's pretty good.
In my code below, it works fine when the user correctly a float. But when they enter some random string, it prints the error message and prompt again for each character. Why is that?
package main
import "fmt"
func readFloat(title string) float64 {
var userInput float64
for {
fmt.Println("Please enter a float: ")
_, err := fmt.Scanf("%f", &userInput)
if err != nil {
fmt.Printf("Wooops! That's not a float
")
} else {
return userInput
}
}
}
func main() {
var f float64
f = readFloat("acceleration")
fmt.Printf("You entered: %.04f
", f)
}
~/src/coursera/go/course-2-functions-methods/week2 $ go run so.go
Please enter a float:
33.3
You entered: 33.3000
~/src/coursera/go/course-2-functions-methods/week2 $ go run so.go
Please enter a float:
sdf
Wooops! That's not a float
Please enter a float:
Wooops! That's not a float
Please enter a float:
Wooops! That's not a float
Please enter a float:
Wooops! That's not a float
Please enter a float: