首页  >  文章  >  后端开发  >  为什么 Scanf 在 Windows 上跳过输入?详细的解释和解决方案。

为什么 Scanf 在 Windows 上跳过输入?详细的解释和解决方案。

Mary-Kate Olsen
Mary-Kate Olsen原创
2024-10-26 18:38:29491浏览

Why Does Scanf Skip Input on Windows? A Detailed Explanation and Solution.

Windows 上的 Scanf 函数怪癖

在使用 Scanf 进行用户输入时,观察到一个奇怪的行为:它第一次成功检索输入,但会跳过第二个输入请求并突然退出该函数。特别是在 Windows 系统上运行时会遇到此问题。

问题代码:

<code class="go">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
}</code>

解决方案:

Scanf 对空格作为分隔符的依赖及其不直观的行为可能会产生问题。为了缓解这种情况,使用 bufio 包提供了一种更精细的方法:

<code class="go">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) // Remove any trailing newline characters
}</code>

以上是为什么 Scanf 在 Windows 上跳过输入?详细的解释和解决方案。的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn