Home >Backend Development >Golang >How to Get Single Character Input in Go Without Pressing Enter?

How to Get Single Character Input in Go Without Pressing Enter?

DDD
DDDOriginal
2024-12-14 09:54:12783browse

How to Get Single Character Input in Go Without Pressing Enter?

Obtaining Character Input Without Pressing Enter in Go

In order to avoid pressing the Enter key after receiving character input in Go, you can utilize the following approach.

  1. Disable Input Buffering:
    Run the command exec.Command("stty", "-F", "/dev/tty", "cbreak", "min", "1").Run() to disable input buffering. This allows the program to read a character immediately upon pressing a key.
  2. Suppress Echo
    Execute the command exec.Command("stty", "-F", "/dev/tty", "-echo").Run() to suppress the display of entered characters on the screen.
  3. Read a Single Byte
    Use os.Stdin.Read(b) to read a single byte (character) from the standard input. This will work even if the user doesn't press Enter after entering a character.
  4. Example
    The following code illustrates how to implement this approach:

    package main
    
    import (
        "fmt"
        "os"
        "os/exec"
    )
    
    func main() {
        // disable input buffering
        exec.Command("stty", "-F", "/dev/tty", "cbreak", "min", "1").Run()
        // do not display entered characters on the screen
        exec.Command("stty", "-F", "/dev/tty", "-echo").Run()
    
        var b []byte = make([]byte, 1)
        for {
            os.Stdin.Read(b)
            fmt.Println("I got the byte", b, "("+string(b)+")")
        }
    }

This solution provides a similar functionality to Console.ReadKey() in C# by allowing you to read a single character without waiting for the user to press Enter.

The above is the detailed content of How to Get Single Character Input in Go Without Pressing Enter?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn