user1978386 user1978386 - 8 months ago 14
Linux Question

How to write a C++ routine which checks which key I've pressed on a keyboard so I can handle each key press separately?

I thought several times about this question but I'd always forget to ask. So how can I write a C/C++ routine which checks what key I pressed so the result is returned immediately after the key has been pressed ? How to accomplish that in Windows ? How to accomplish that in Linux ? What headers I should include if I use Dev-C++ and Code::Blocks ?

I try this:

#include <iostream>
#include <conio.h>

int main(void)
using namespace std ;
cout << "Press a key" << endl ;
char key ;
getch() >> key ;
cout << "\nYou have pressed: " << key << endl ;
return 0 ;

but it doesn't tell me what key I pressed. How to get a key value ?


You can use the getch() function from <conio.h>, for example:

int c;
c = getch();

There is also a GetAsyncKeyState function: you might find useful.