首頁  >  文章  >  後端開發  >  為什麼 Go 中 fmt.Scanf() 會導致無限迴圈且輸入無效?

為什麼 Go 中 fmt.Scanf() 會導致無限迴圈且輸入無效?

Patricia Arquette
Patricia Arquette原創
2024-10-27 04:23:30356瀏覽

Why Does fmt.Scanf() Cause an Infinite Loop with Invalid Input in Go?

Go 的fmt.Scanf 中如何處理無效輸入

對於那些在使用fmt.Scanf() 時遇到無效輸入問題的人來說,這是對於理解為什麼當輸入字串而不是整數時程式會進入無限循環至關重要。

在Go 中,fmt.Scanf() 會解析輸入流以取得特定的格式說明符(例如,「%d」 " 對於十進位整數)。無效輸入(例如字串)會導致錯誤,但輸入仍保留在Stdin 緩衝區中。

另一種方法是使用fmt.Scanln(),其行為不同。 🎜>

其他選項

<code class="go">fmt.Printf("Please enter an integer: ")

// Read in an integer
var i int
_, err := fmt.Scanln(&i)
if err != nil {
    fmt.Printf("Error: %s", err.Error())

    // If int read fails, read as string and forget
    var discard string
    fmt.Scanln(&discard)
    return
}
fmt.Printf("Input contained %d", i)</code>
如果fmt.Scanln() 不是最佳的,其他選項包括:

重置Stdin 緩衝區:

使用bufio.Reader.Reset() 或bufio.NewReader() 清除緩衝區。有效輸入的循環。

以上是為什麼 Go 中 fmt.Scanf() 會導致無限迴圈且輸入無效?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

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