Adam Adam - 15 days ago 11
C Question

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

I can never remember how I do this because it comes up so infrequently for me. But in C or C++, what is the best way to read a character from standard input without waiting for a newline (press enter).

Also ideally it wouldn't echo the input character to the screen. I just want to capture keystrokes with out effecting the console screen.

Answer

That's not possible portably 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 function _getch() 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.