I'm new to GoLang and I have the problem that if I type in multiple letters as a input the outcome will print multiple times.
The user needs to type a number that isn't 0 and isn't letters. If you type a letter the variable 'num1' will be '0' (checked by printing the variable)
If the user types '0' or letters he will get another try to type in a number.
Example: If I type "d" it will print once as it should be. If I type "dd" it will print twice. If I type "ddd" it will print three times. But if I type "0" or "00" it will print only once as it should be.
How can I make it so that if I type multiple letters the outcome will always print once?
Code:
package main
import "fmt"
func main() {
var num1 float64
for {
fmt.Print("\nFirst Number: ")
fmt.Scanln(&num1)
if num1 == 0 {
fmt.Print("Invalid input for 'First Number'")
} else {
break
}
}
fmt.Print("passed")
}
PS: The variable num1 should stay as 'float64' if possible
Thanks for the help ^^
The problem you are facing is that the fmt.Scan when fails to convert the string to float, the unscanned bits remain in buffer. You can try to clear the buffur by actually reading and ignoring it.
func main() {
var num1 float64
stdin := bufio.NewReader(os.Stdin)
for {
fmt.Print("\nFirst Number: ")
fmt.Scan(&num1)
if num1 == 0 {
stdin.ReadString('\n')
fmt.Print("Invalid input for 'First Number'")
} else {
break
}
}
fmt.Print("passed")
}
I would recommend another approch my manually parsing the float from string like this:
func main() {
var num1 float64
for {
var input string
var err error
fmt.Print("\nFirst Number: ")
fmt.Scan(&input)
num1, err = strconv.ParseFloat(input, 64)
if err != nil {
fmt.Print("Invalid input for 'First Number'")
}
if num1 == 0 {
fmt.Print("Invalid input for 'First Number'")
} else {
break
}
}
fmt.Print("passed")
}
And always make sure to read the errors and understand them.