Is there a way to run a bit of code when a key is pressed?

I've been wondering for a while if there is a way to run some code when you press a certain key. for instance:

When the key 'M' is pressed, then:
cout << "'M' key pressed!" << endl;

How do I do this?
There is no standard for this. Your best bet is to look into your OS's API for something. Duoas has an article about doing something similar with the Windows API.
getch is the non-standard function for this, but this may also do the trick: http://www.cplusplus.com/articles/yAUq5Di1/
closed account (zwA4jE8b)
if you want portability you can use SDL, then your program will work on linux and windows.

in short

1
2
3
4
5
6
while(SDL_PollEvent(&event)
{
  if event.type ==SDL_KEYDOWN
    if event.key.keysym.sym == SDLK_m
      std::cout << 'M' key pressed!" << std::endl;
} 
or SFML, which doesn't use ugly capitals and is written in C++ instead of C.

just sayin'
Is there any reason this can't be done? Like something I dont know about?

if(GetAsyncKeyState(VK_UP))
{
std::cout << "You pressed up";
}

Or is it because that is just for Windows?
Only for windows, but I don't believe it "just works" like that. I could be wrong, however.
closed account (zwA4jE8b)
I believe that is the wrong syntax for getasynckeystate() but it is rather easy to use.
It probably is the wrong syntax or something. I havent used it in a long time.
Topic archived. No new replies allowed.