GOLang Scanf错误 [英] GOLang Scanf error

查看:79
本文介绍了GOLang Scanf错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

第一次使用Scanf两次时,它将获得用户输入,而第二次则没有,并退出该功能.这仅是在Windows上运行时的问题.当我在Mac上运行它时,它可以按预期工作,首先要求用户提供用户名,然后输入密码.下面是有问题的代码.我不确定为什么它在Mac上能正常运行,但在Windows上却不能正常运行.提前任何帮助表示赞赏.谢谢.

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有点挑剔,因为它使用空格作为分隔符,并且(至少对我而言)是不直观的.Bufio在抽象其中的一些方面做得很好:

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
}

这篇关于GOLang Scanf错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆