C++, getting input from console

Started by
3 comments, last by Ectara 9 years, 10 months ago

Hi,

I am programming my first game framework in c++ and I have a console where I print debug info. Now I want to be able to introduce commands. The problem is that I dont know how to get the console input without pausing the main game loop. How can I do it? Do I need to separate it in another thread?

Thanks.

Advertisement
Yes, using a separate thread is certainly a solution. You can also check if there is input available in a non-blocking manner, but the language doesn't provide a standard way to do this, so you need to rely on platform-specific solutions.

Here's a POSIX implementation (I use this on Linux and Mac OS X):
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>

bool is_there_input() {
  struct timeval tv = {0l, 0l};
  fd_set rfds;
  FD_ZERO(&rfds);
  FD_SET(0, &rfds);

  return select(1, &rfds, 0, 0, &tv);
}
Check your compiler's non standard console headers. Most ship with something like getkey() or something that checks for a key press but returns immediately if none down.

You can poll this in your main loop. Threading is probably overkill for this and brings a host of its own complications

If you are using Win32 there are facilities in the Win32 console API to respond to key events asynchronously too.

kbhit() is provided in conio.h, if your compiler supports it. That's a simple way to check if a keyboard key has been hit without blocking.

example

My Gamedev Journal: 2D Game Making, the Easy Way

---(Old Blog, still has good info): 2dGameMaking
-----
"No one ever posts on that message board; it's too crowded." - Yoga Berra (sorta)

Hi,

I am programming my first game framework in c++ and I have a console where I print debug info. Now I want to be able to introduce commands. The problem is that I dont know how to get the console input without pausing the main game loop. How can I do it? Do I need to separate it in another thread?

Thanks.

From reading this, I can't tell if you're talking about outputting to the OS's console, or a shell, or if you have a custom graphical console within the application's window.

If the former, as mentioned, you could try kbhit() in Windows, or using termio in *nix, or something else like that.

If the latter, you could poll for input if you determine that the console has focus, and filter out the key presses that you want into a line buffer, before submitting it for parsing.

Neither of these solutions require a separate thread, but if you really, really want to, you can spend a thread on it.

This topic is closed to new replies.

Advertisement