2

I am writing an application for a robot.

The required UI for the application is described in the pseudo-code below:

 while(true){
      if (spacebar is not pressed){
           //do something
      }
      else{
           sleep(1); //wait for a second
      }     
 }

If I use cin or some other console input reading function then it will wait for user to press something. How do I ensure that it does not wait to get any input?

I am using Ubuntu. But I do not want it to be OS-specific.

Answers here seem to be OS specific.

Community
  • 1
  • 1
Manas Paldhe
  • 766
  • 1
  • 10
  • 32
  • What OS are you using? – Mats Petersson Jul 09 '13 at 14:53
  • 2
    possible duplicate of [C non-blocking keyboard input](http://stackoverflow.com/questions/448944/c-non-blocking-keyboard-input) – Mats Petersson Jul 09 '13 at 14:54
  • 1
    Unfortunately, either your code will need to be OS specific, or you will need to find a cross-platform library that hides the OS-specifics from you. C++ does not give you a portable way to do this. – Joe Z Jul 09 '13 at 14:55

2 Answers2

1

Terminal Level input

What you are asking for is fairly close to the hardware (key-press / key-release) compared to the "standard input/output" stream concepts. So your implementation would have to be OS specific. Having said that the library to use is curses[1] which has been around for a long time and is standard on a lot of Un*x platforms. The GNU ncurses flavor compiles for pretty much all of them, it is a standard install in almost all Linux environments, and where it isn't installed by default you can find it. It also works well in Windows (cygwin), os/2 and a bunch of embedded systems etc. so you should be able to write a fairly portable software using curses that does what you want.

Ahmed Masud
  • 21,655
  • 3
  • 33
  • 58
0

It's not too clear what you're asking for. In the if, is the condition based on whether a space character has been entered, or whether the user is currently holding down the space bar? In the first case, you need something like curses (a portable library which does gets each character as it was entered, without echo). In the second, I don't think that there is a portable solution. Even non-portably, you might not be able to get it if your program is reading from a terminal window (e.g. xterm); this sort of information is typically only present as window events, when you created the window in your program.

James Kanze
  • 150,581
  • 18
  • 184
  • 329