C language getch of function details and simple examples
- 2020-05-17 05:59:12
- OfStack
The getch() function in C language
Preface:
This function is a non-echo function, when the user presses a character, the function automatically read, do not need to press enter, some C language command line program will use this function to play games, but this function is not a standard function, to pay attention to portability!
So there is such an interface, it is very niuobu, at least can make a game to play, combined with ASCII code, it is easy to write a direction key control 2048 or snake and other interesting games.
Here is a simple example:
You will find that when you press the corresponding button it will print the corresponding statement.
#include <stdio.h>
#include <fcntl.h>
#include <stdlib.h>
#include <conio.h>
#define ESC 0x1B
#define ENTER 0x0D
#define SPACE 0x20
#define KEY_UP 72 // on
#define KEY_DOWN 80 // Under the
#define KEY_LEFT 75 // On the left
#define KEY_RIGHT 77 // right
int KEY_EXIT_STATU = 0 ;
int KEY_ENTER_STATU = 0 ;
int KEY_SPACE_STATU = 0 ;
int KEY_UP_STATU = 0 ;
int KEY_DOWN_STATU = 0 ;
int KEY_LEFT_STATU = 0 ;
int KEY_RIGHT_STATU = 0 ;
char ch ;
int get_value() ;
int main(void)
{
int i = 0;
while(1)
{
get_value();
}
return 0 ;
}
int get_value()
{
ch = getch() ;
system("cls");
switch(ch)
{
case ESC : KEY_EXIT_STATU = 1 ;
printf(" exit \n") ; break ;
case ENTER :KEY_ENTER_STATU = 1 ;
printf(" enter \n") ; break ;
case SPACE :
KEY_SPACE_STATU = 1 ;
printf(" The blank space \n") ; break ;
case KEY_UP:case 'w' :
KEY_UP_STATU = 1 ;
printf(" on \n") ; break ;
case KEY_DOWN:case 's' :
KEY_DOWN_STATU = 1 ;
printf(" Under the \n") ; break ;
case KEY_LEFT:case 'a' :
KEY_LEFT_STATU = 1 ;
printf(" On the left \n") ; break ;
case KEY_RIGHT:case 'd':
KEY_RIGHT_STATU = 1 ;
printf(" right \n") ; break ;
}
}
Thank you for reading, I hope to help you, thank you for your support of this site!