首頁  >  文章  >  後端開發  >  為什麼 Windows 上的 Go 第二次輸入時 Scanf 會失敗?

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

DDD
DDD原創
2024-10-26 11:14:29558瀏覽

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

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn