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

為什麼 Scanf 在 Windows 上跳過輸入?詳細的解釋和解決方案。

Mary-Kate Olsen
發布: 2024-10-26 18:38:29
原創
490 人瀏覽過

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中文網其他相關文章!

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