probably a stupid question, but I haven't been able to find anything.

Is there a istream related function that let me read exactly one keystroke
from the keyboard through cin?

What I need it to do is this:
- remove all characters currently in the input buffer
- block until the user presses a key
- return the ascii code of the key that was pressed

This should work also, if the user just hit the enter key.

I'm probably too stupid to get it right, but the usual get/getline()
functions always block until the user hits enter, even if the user enteres
other keys before, but on the other hand, if the user presses enter only,
getline continues to block and does not return the empty line.

Ideally I would like somethink like this:

1. a menu, where the user can press 1, 2 or 3 (and the program reactiving
immediately without the need for the user to press enter afterwards)
2. a "Press any key to continue" function, that waits for exactly one
keystroke, no matter what key it is.

thank you

8 Years
Discussion Span
Last Post by iamthwee

There isn't anything standard that would do that, so you lose any chance of code portability.

What compiler and OS are you using.


If you're on Windows: system("PAUSE"); may be what you're looking for, though you can't get the character that was pressed, if that's also what you wanted (wasn't sure).


Like iamthwee indicated, there is no standard way to do that. You'll have to do something OS-specific.

I suggest you check out the Curses library.

POSIX: NCurses
Win32: PDCurses

Hope this helps.


You may already have NCurses installed.

Try the following program to see if you do.

// hello.cpp

#include <curses.h>

int main() {
  intrflush( stdscr, FALSE );
  keypad( stdscr, TRUE );

  mvaddstr( 10, 10, "Hello, world" );
  mvaddstr( 11, 10, "Press the 'any' key." );

  wgetch( stdscr );

  return 0;

Compile with g++ -o hello hello.cpp -lncurses .

The code is valid C code also, so it doesn't matter if you use gcc or g++.

If it complains that it doesn't know what libncurses is, try -lcurses, and if that fails, use sudo apt-get install ncurses-dev and that should (hopefully) get you everything you need.

Hope this helps.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.