2

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..

2
  • 1
    What OS & compiler are you using?
    – Mike Nakis
    Commented Jan 4, 2012 at 18:34
  • @MikeNakis Windows 7 Ultimate x86 and code::blocks with GNU GCC compiler Commented Jan 4, 2012 at 18:36

4 Answers 4

3

WIndows kbhit( ) does exactly this non-blocking keyboard char-ready check, and there's a kbhit( ) for Linux over here

3
  • 1
    thank 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
2

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.

1
  • 1
    thank you.. kbhit() with getch() to retrieve what's been pressed works awesome.. :) Commented Jan 5, 2012 at 9:47
0

you should use select or poll

0

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.

1
  • 1
    Well, that elusive "non-blocking input read" is precisely what he is asking for.
    – Mike Nakis
    Commented Jan 4, 2012 at 19:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.