Use a clever method to implement the getch () function.

Source: Internet
Author: User

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.


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.