首頁 > 後端開發 > Golang > 主體

為什麼 Windows 上的 Go 第二次輸入時 Scanf 會失敗?

DDD
發布: 2024-10-26 11:14:29
原創
578 人瀏覽過

Why Does Scanf Fail on Second Input in Go on Windows?

在Windows 上的GOLang 中使用Scanf 時出錯

GOLang 中的Scanf 函數在嘗試兩次獲取使用者輸入時可能會出現問題。第一次輸入已成功檢索,但在 Windows 系統上第二次嘗試期間該函數突然終止。此行為在 macOS 上不會發生。

<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 trailing newline character
}</code>
登入後複製

此修改後的程式碼解決了該問題,並在 Windows 和 macOS 上無縫運行。

以上是為什麼 Windows 上的 Go 第二次輸入時 Scanf 會失敗?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!