Use a clever method to implement the getch () function.
To use the getch () function, you must first introduce the conio. h header file.
However, I use cygwin as the compiling environment and cannot find conio. h. Therefore, I can only find an alternative method or construct a function with similar functions by myself.
Unfortunately, it wasn't long before I learned programming. At the moment, I didn't think of a proper alternative method. If I say I constructed this function myself, it would be even harder.
So Baidu finally found a clever way.
The principle is: temporarily disable the terminal cache and use getchar () to directly obtain the buttons, instead of waiting for the Enter key to take effect.
The test code is as follows:
1 #include <stdio.h>
2 #include <stdlib.h>
3
4 int my_getch (void);
5
6 int main (void) {
7
8 while ('q'! = My_getch ()) {
9 printf ("hello \ n");
10}
11
12 return 0;
13}
14
15
16
17 int my_getch (void) {
18 char a;
19 system ("stty -icanon"); // Close the terminal buffer
20 system ("stty -echo"); // Close terminal echo
21 a = getchar ();
22 system ("stty icanon"); // Open the terminal buffer
23 system ("stty echo"); // Open terminal echo
24 return a;
25}
The same principle can be used to implement the function of the getche () function, which is not described here.