首頁  >  文章  >  後端開發  >  為什麼 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