Matt Munson
Matt Munson

Reputation: 3003

C++, how to control program flow with keyboard input

I have a main routine that loops infinitely. By changing bool variables using keyboard input, I want to be able to control whether certain if{} statements within that loop are getting called. I found this thread:
C non-blocking keyboard input,
but it seems excessively laborious and complicated for seemingly basic functionality. Is there an easier way to do it?

Upvotes: 1

Views: 3182

Answers (3)

OJW
OJW

Reputation: 4632

Put the main routine in a thread, then have something like

static char mode = ' ';
while(mode != 27) // to allow Esc to end program
{
  mode = _getch();
}

Threaded code can then do different things based on what key was pressed.

Upvotes: 1

Martin Stone
Martin Stone

Reputation: 13007

The SDL library is one way to do it cross-platform. Here's an example of polling keyboard events.

Upvotes: 1

Klaim
Klaim

Reputation: 69752

You'll have to use the OS/Firmware/Framework/environment API to get input events, or use a library that do this for you. Anyway, there is no built-in way of doing this in C++.

I often use OIS in games. It's cross-platform and easy to use. Not sure it's useful for other cases than games but it does the job for you.

Upvotes: 4

Related Questions