When a user interacts with a command-line application, pressing a key often requires them to press Enter to submit their input. However, some scenarios require immediate character recognition without the Enter key. How can this be achieved in Go for Windows systems?
For Windows systems, you can disable input buffering and hide entered characters from the screen using the following steps:
1. // disable input buffering exec.Command("stty", "-F", "/dev/tty", "cbreak", "min", "1").Run() 2. // do not display entered characters on the screen exec.Command("stty", "-F", "/dev/tty", "-echo").Run()
With these commands in place, you can use the following code to read characters without pressing Enter:
var b []byte = make([]byte, 1) for { os.Stdin.Read(b) fmt.Println("I got the byte", b, "("+string(b)+")") }
When you run this program, it will display a message prompting the user to press any key to exit. Pressing any key will trigger the os.Stdin.Read(b) call, which will return the character pressed and display it on the screen.
The above is the detailed content of How to Read Single Characters from Console Input in Go Without Pressing Enter?. For more information, please follow other related articles on the PHP Chinese website!