In Windows, in Visual Studio (VS), you can use the _kbhit() function to get keyboard events. When using it, you need to include the conio.h header file, e.g.:
Example
#include <conio.h>
#include <iostream>
using namespace std;
int main()
{
int ch;
while (1){
if (_kbhit()){// If a key is pressed, the _kbhit() function returns true
ch = _getch();// Use the _getch() function to get the value of the pressed key
cout << ch;
if (ch == 27){ break; }// When ESC is pressed, exit the loop; the key value of the ESC key is 27.
}
}
system("pause");
}
On Unix/Linux, the kbhit() function is not provided. We can implement kbhit() ourselves.
Example
#include <stdio.h>
#include <termios.h>
static struct termios initial_settings, new_settings;
static int peek_character = -1;
void init_keyboard(void);
void close_keyboard(void);
int kbhit(void);
int readch(void);
void init_keyboard()
{
tcgetattr(0,&initial_settings);
new_settings = initial_settings;
new_settings.c_lflag |= ICANON;
new_settings.c_lflag |= ECHO;
new_settings.c_lflag |= ISIG;
new_settings.c_cc[VMIN] = 1;
new_settings.c_cc[VTIME] = 0;
tcsetattr(0, TCSANOW, &new_settings);
}
void close_keyboard()
{
tcsetattr(0, TCSANOW, &initial_settings);
}
int kbhit()
{
unsigned char ch;
int nread;
if (peek_character != -1) return 1;
new_settings.c_cc[VMIN]=0;
tcsetattr(0, TCSANOW, &new_settings);
nread = read(0,&ch,1);
new_settings.c_cc[VMIN]=1;
tcsetattr(0, TCSANOW, &new_settings);
if(nread == 1)
{
peek_character = ch;
return 1;
}
return 0;
}
int readch()
{
char ch;
if(peek_character != -1)
{
ch = peek_character;
peek_character = -1;
return ch;
}
read(0,&ch,1);
return ch;
}
int main()
{
init_keyboard();
while(1)
{
kbhit();
printf("\n%d\n", readch());
}
close_keyboard();
return 0;
}