从 Stdin 读取 Go 中的特殊键
在 Go 中从 stdin 读取用户输入时,通常需要检测特殊键,例如“输入”或“退格”以执行特定命令或编辑操作。为了实现这一目标,让我们探索一种合适的方法来解释这些特殊键。
在提供的代码片段中,程序不断读取 stdin 并将输入附加到字符串中。为了检测特定的键,我们需要确定它们相应的字节数组或字符串表示形式。
为了找到这些值,我们可以利用像 termbox-go 这样的库。它提供了一个事件驱动的接口,允许我们捕获按键及其相关代码。
使用 termbox-go 考虑以下代码:
package main import ( "fmt" term "github.com/nsf/termbox-go" ) func main() { err := term.Init() if err != nil { panic(err) } defer term.Close() fmt.Println("Press any key to see their ASCII code or press ESC button to quit") keyPressListenerLoop: for { switch ev := term.PollEvent(); ev.Type { case term.EventKey: switch ev.Key { case term.KeyEsc: break keyPressListenerLoop case term.KeyEnter: // Handle enter key press case term.KeyBackspace: // Handle backspace key press // Add other special keys here } case term.EventError: panic(ev.Err) } } }
此代码设置一个事件侦听器使用 termbox-go 并等待按键事件。当按下某个键时,代码会检查其类型和键代码。基于按键代码,可以实现自定义逻辑来处理特定按键,例如“enter”或“backspace”。例如:
case term.KeyEnter: fmt.Println("Enter key pressed") case term.KeyBackspace: fmt.Println("Backspace key pressed")
或者,如果唯一的要求是检测“enter”按键,则可以使用更简单的方法:
package main import ( "fmt" "os" "bufio" ) func main() { fmt.Println("Press ESC button or Ctrl-C to exit this program") fmt.Println("Press Enter to continue") for { consoleReader := bufio.NewReaderSize(os.Stdin, 1) fmt.Print("> ") input, _ := consoleReader.ReadByte() ascii := input // ESC = 27 and Ctrl-C = 3 if ascii == 27 || ascii == 3 { fmt.Println("Exiting...") os.Exit(0) } if ascii == 10 { // Enter key has ASCII value 10 fmt.Println("Enter key pressed") } } }
此代码使用 bufio 的 consoleReader 来读取一次单个字符,使其能够检测“enter”键按下。
通过利用这些方法,开发人员可以有效地处理特殊键从 stdin 读取时在 Go 程序中的输入。
以上是如何从 Go 的标准输入中检测特殊键(例如 Enter 和 Backspace)?的详细内容。更多信息请关注PHP中文网其他相关文章!