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?
Asked
Active
Viewed 2,208 times
3 Answers
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
-
That would be very unusual - it is not the default behaviour. – Jonathan Leffler Jul 23 '11 at 07:04
1
char c = getchar();
It should do the trick.

Mark Segal
- 5,427
- 4
- 31
- 69
-
2
-
3with 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