2

Possible Duplicate:
C/C++: Capture characters from standard input without waiting for enter to be pressed
How do you do non-blocking console I/O on Linux in C?

I am attempting to write a program in the C language which is in a constant loop but I need to be able to receive input from the keyboard at the start of each cycle or to continue on if there is no key being pressed.

getchar() and _getch() are insufficient as they both wait for the input. If anybody knows of a function similar to _getch but which doesn't wait for the input it would be much appreciated.

Community
  • 1
  • 1
user1898185
  • 41
  • 1
  • 1
  • 2

1 Answers1

5

There's no C-standard way to do what you want to do (capture keystrokes from the keyboard without the user hitting enter), you have to go platform specific. <conio.h> should have what you need on Windows, you'd need curses on Linux to get this. (I suspect curses would work on Mac as well, but don't quote me on that)

On Windows kbhit() doesn't wait for any input, it just returns if there is a key pressed at the very instant you make the test. If you need to know what the key was as well, then you can combine this with getch()

something like:

while(countdown++ <= 1000){  // give a second to hit something
    if(b=kbhit())            // if the user presses a key
        break;               // leave the loop early
    Sleep(1);                // else, sleep for 1 ms and try again
}
if (b != 0)          // if something was pressed
    printf("The key was %d\n", getch());
Mike
  • 47,263
  • 29
  • 113
  • 177