英文:
GOLang Scanf error
问题
当使用Scanf两次时,第一次它会获取用户的输入,但第二次它不会,并且返回函数。这只是在Windows上运行时的问题。当我在我的Mac上运行它时,它按预期工作,首先询问用户的用户名,然后是密码。以下是相关的代码。我不确定为什么它在Mac上运行良好,但在Windows上不行。提前感谢任何帮助。谢谢。
func credentials() (string, string) {
var username string
var password string
fmt.Print("输入用户名:")
fmt.Scanf("%s", &username)
fmt.Print("输入密码:")
fmt.Scanf("%s", &password)
return username, password
}
英文:
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
}
答案1
得分: 13
Scanf在使用上有点棘手,它使用空格作为分隔符,并且(至少对我来说)不太直观。Bufio在抽象化这方面做得很好:
func credentials() (string, string) {
reader := bufio.NewReader(os.Stdin)
fmt.Print("输入用户名:")
username, _ := reader.ReadString('\n')
fmt.Print("输入密码:")
password, _ := reader.ReadString('\n')
return strings.TrimSpace(username), strings.TrimSpace(password) // ReadString()会留下一个尾随的换行符
}
英文:
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
}
答案2
得分: 0
你需要添加换行符:
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)
}
或者,你可以直接使用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
英文:
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)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论