5

I'm using scanf() to read user input on terminal in a console application. scanf waits until the user hits the return key to read. Is there a way to read the user input on each keystroke?

Foo Bah
  • 25,660
  • 5
  • 55
  • 79
the Reverend
  • 12,305
  • 10
  • 66
  • 121

3 Answers3

5

The usual way would be to use the getch function from (the Mac port of) ncurses.

Note that while getchar reads a single character, it still normally does buffered reading, so you need to press 'return'/'enter' before it'll return.

Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111
3

getch() returns the character stream from stdin as it is typed.

Paul Sonier
  • 38,903
  • 3
  • 77
  • 117
1
char c = getchar();

It should do the trick.

Mark Segal
  • 5,427
  • 4
  • 31
  • 69
  • 2
    why ? he wants a `char` - and an `int` takes more memory – Mark Segal Jul 22 '11 at 22:23
  • 3
    with int you can check for out-of-band values, also, when declared as local variable it will probably take the same place. – MByD Jul 22 '11 at 22:27
  • 2
    @Quantic: getchar() returns an int, so it can return any normal char as well as a non-char value like EOF. – Rudy Velthuis Jul 22 '11 at 22:28
  • I didn't quite understand what 'out-of-band' values mean - please explain – Mark Segal Jul 22 '11 at 22:28
  • There are values that does not fit in `char` (as @Rudy Velthuis said) and you cannot detect them when you use a char. – MByD Jul 22 '11 at 22:35
  • EOF is a value different from any valid `char` - so you can't reliably store the result of `getchar()` in a `char` because it can return any valid `char` and EOF. – Jonathan Leffler Jul 23 '11 at 07:05