views:

606

answers:

3

And I know there's std::cin, but that requires the user to enter a string, then press ENTER. Is there a way to simply get the next key that is pushed without needing to press ENTER to confirm

+8  A: 

What you're looking for is related to manipulating the console, and is OS-dependent. If you're in a UNIX-based OS, check out the curses library, and in Windows, there are getch() and kbhit() functions from <conio.h>.

Jesse Beder
pdcurses is portable.
Bastien Léonard
+1  A: 

In order to read the keyboard you need to step out of the C++ and use the C-runtime library, look in conio.h - getch

Anders K.
+3  A: 

You can use

#include <conio.h>

and then catch char with cases such as this

char c;
if (_kbhit())
{
  c = getch();
  switch(c)
  {
  case ‘\0H’ :
  cout << "up arrow key!" << endl;
  break;
  }
}

Beware: I have not tried it... and remember to put the whole thing into a "while(true)" to test.

Dervin Thunk
I assume that <conio.h> and _kbhit() are windows/DOS specific?
camh
Also, hoe does '\OH' translate into up arrow? (As in, what are the values of the down, left, and right arrows?)
Keand64
@camh: yes, afaik@Kean64: if i remember correctly, there are constants like ARROW_KEY_UP, please try that. not in front of my devel computer...
Dervin Thunk