Capture characters from standard input without waiting for enter to be pressed

That’s not possible in a portable manner in pure C++, because it depends too much on the terminal used that may be connected with stdin (they are usually line buffered). You can, however use a library for that:

  1. conio available with Windows compilers. Use the _getch() function to give you a character without waiting for the Enter key. I’m not a frequent Windows developer, but I’ve seen my classmates just include <conio.h> and use it. See conio.h at Wikipedia. It lists getch(), which is declared deprecated in Visual C++.

  2. curses available for Linux. Compatible curses implementations are available for Windows too. It has also a getch() function. (try man getch to view its manpage). See Curses at Wikipedia.

I would recommend you to use curses if you aim for cross platform compatibility. That said, I’m sure there are functions that you can use to switch off line buffering (I believe that’s called “raw mode”, as opposed to “cooked mode” – look into man stty). Curses would handle that for you in a portable manner, if I’m not mistaken.

Leave a Comment