I'm trying to make Tetris game in standard console. I need non-blocking getch(), so the blocks can fall without pressing any key. It would be nice to have function that returns -1 if no key pressed, otherwise the key code.
Asked
Active
Viewed 2.0k times
10
-
You'll need to have an infinite loop and handle _keypress_ events inside of it. – SingerOfTheFall Jul 13 '12 at 14:06
-
@RobKennedy - dupe assumes using ncurses – Martin Beckett Jul 13 '12 at 14:10
-
@kittyPL, what OS and compiler are you using? As you might infer from the duplicate vote, `getch()` is a non-standard function. Functions with that name are provided in the MS Windows API and in a Unix library called "curses". Other than coincidentally sharing a name, those functions are wholly unrelated. – Robᵩ Jul 13 '12 at 14:58
-
1This is not a duplicate. This question about **non-blocking** getch and the duplicate is about **blocking** getch (the OP wanted it to be blocking where it was non-blocking due to incorrect usage of the library, which is hardly a solution). – Thomas Dec 30 '13 at 00:32
2 Answers
19
This is exactly what you wanted:
int getch_noblock() {
if (_kbhit())
return _getch();
else
return -1;
}
Basically kbhit()
does the job of determining if a key is pressed.
Assumes Windows and Microsoft Visual C++.

quantum
- 3,672
- 29
- 51
10
It's operating system specific but your library probably has a function called kbhit() or similar that will do this

Martin Beckett
- 94,801
- 28
- 188
- 263