When using Scanf twice the first time it gets the useres input but the second time it does not and returns out of the function. This is only a problem when running on Windows. When I run it on my Mac it works as expected first asking the uers for their username then their password. Below is the code in questions. I am not sure why it works fine on Mac but not on Windows. Any help in advance is appreciated. Thank you.
func credentials() (string, string) {
var username string
var password string
fmt.Print("Enter Username: ")
fmt.Scanf("%s", &username)
fmt.Print("Enter Password: ")
fmt.Scanf("%s", &password)
return username, password
}
Scanf is a bit finicky in that it uses spaces as a separator, and (at least for me) is rather unintuitive. Bufio does a good job of abstracting some of that:
func credentials() (string, string) {
reader := bufio.NewReader(os.Stdin)
fmt.Print("Enter Username: ")
username, _ := reader.ReadString('\n')
fmt.Print("Enter Password: ")
password, _ := reader.ReadString('\n')
return strings.TrimSpace(username), strings.TrimSpace(password) // ReadString() leaves a trailing newline character
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With