Is there a C function that doesn't wait for input but if there is one, it detects it? What I'm trying to do here is continue a loop endlessly until any key is pressed. I'm a newbie, and all the input functions I've learned so far waits for the user to input something.. I hope I'm clear, although if I'm not I'm happy to post the code..
4 Answers
WIndows kbhit( ) does exactly this non-blocking keyboard char-ready check, and there's a kbhit( ) for Linux over here
-
1thank you.. kbhit() with getch() to retrieve what's been pressed works awesome.. :) Commented Jan 5, 2012 at 9:50
-
@Shashwat Mehta -- Good for you! Thanks for the feedback. Please don't forget to accept this answer if it works out for you. Commented Jan 5, 2012 at 10:00
-
Link "pwilson.net/kbhit.html" --> ERR_NAME_NOT_RESOLVED Oct 2021 Commented Oct 20, 2021 at 15:59
Since nobody's stated it clearly....
The important thing to note is that the standard library provided by C does not provide the capability you're looking for. Achieving it, then, requires the use of third party libraries and/or special knowledge about the operating system you're using.
Typically, you'll have some of those third-party libraries available. If you were using Visual Studio, for example, you would be able to use http://msdn.microsoft.com/en-us/library/58w7c94c(v=VS.100).aspx. I'm not sure what's available to you with your setup.
-
1thank you.. kbhit() with getch() to retrieve what's been pressed works awesome.. :) Commented Jan 5, 2012 at 9:47
You might also want to check signal() if all you need is a way to stop the loop and run your end of the program function.
It depends what you exactly want to do, but in general:
A) You keep your program single-threaded and check input through a non-blocking input read.
B) You spawn a different thread that will handle the input and communicate the results back to the main thread.
-
1Well, that elusive "non-blocking input read" is precisely what he is asking for. Commented Jan 4, 2012 at 19:00