Reputation: 949
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
}
Upvotes: 6
Views: 4600
Reputation: 1
You need to add newlines:
package main
import "fmt"
func main() {
var user, pass string
fmt.Scanf("%s\n", &user)
fmt.Println(user)
fmt.Scanf("%s\n", &pass)
fmt.Println(pass)
}
alternatively, you can just use Scanln
:
package main
import "fmt"
func main() {
var user, pass string
fmt.Scanln(&user)
fmt.Println(user)
fmt.Scanln(&pass)
fmt.Println(pass)
}
https://golang.org/pkg/fmt#Scanln
Upvotes: 1
Reputation: 17535
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
}
Upvotes: 13