首頁  >  文章  >  後端開發  >  為什麼Golang的scanf函數在Windows上失敗,但在Mac上卻可以?

為什麼Golang的scanf函數在Windows上失敗,但在Mac上卻可以?

Patricia Arquette
Patricia Arquette原創
2024-10-26 17:43:02881瀏覽

Why Does Golang's Scanf Function Fail on Windows But Work on Mac?

GOLang Scanf 錯誤:為什麼它在 Windows 上失敗而在 Mac 上失敗

尋求使用者輸入是程式設計中的常見任務。在 GOLang 中,Scanf 函數經常用於此目的。然而,使用 Scanf 兩次時會出現一個特殊的問題:它在 macOS 上可以運行,但在 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>

在 macOS 上執行時,程式會提示user 的使用者名稱和密碼,如預期的那樣。然而,在 Windows 上,在提示輸入使用者名稱後,程式會忽略密碼提示並突然退出。

造成這種差異的原因在於 Scanf 解釋使用者輸入的方式。在 Windows 上,Scanf 使用回車符 (r) 作為預設行終止符,而 macOS 使用換行符 (n)。當輸入使用者名稱並按 Enter 時,Scanf 遇到回車並將其解釋為輸入終止符。結果,程式跳過第二個 Scanf 行並退出。

要在 Windows 上解決此問題,我們可以使用 Bufio,一個為 I/O 操作提供緩衝的函式庫。 Bufio 提供了 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) // ReadString() leaves a trailing newline character
}</code>

此版本使用 ReadString 讀取使用者的輸入。 ReadString 接受分隔符,在本例中為換行符「n」。這確保了即使在 Windows 上也能正確讀取使用者名稱和密碼,因為行終止符已正確處理。

總而言之,Scanf 在不同作業系統上表現出不一致的行為,這可歸因於不同的行終止約定。透過使用 Bufio,開發人員可以克服這些不一致問題,並依靠更可靠的方法來捕獲跨不同平台的使用者輸入。

以上是為什麼Golang的scanf函數在Windows上失敗,但在Mac上卻可以?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

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