Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ cin keypress event

I believe this is a very simple question, but I can't find a simple answer to it. I have an infinite loop, e.g. while(1), for(;;), and I need to break from the loop on a keypress. What is the easiest way to do this?

P.S.: I can't use getch, cin.ignore, or cin.get because it stops the loop.

like image 677
Lukas Salich Avatar asked Aug 16 '12 13:08

Lukas Salich


1 Answers

Well, what you want is asynchronous input. All of the methods provided by cin wait for enter. You will have to use system-specific functions for that, or use a library that will do it for you.

What you need to do is to not only process your logic in a while loop, but also listen from message pipe from your OS. If you want some more information about that one, please drop a comment.

EDIT: There's one other way, but I wouldn't recommend it as it can be non-portable I believe. The following code compiles and runs under VS2012RC.

#include<iostream>
#include<conio.h>

using namespace std;

int main()
{
   cout << "Enter a character";
   getch();
}
like image 52
Bartek Banachewicz Avatar answered Sep 22 '22 16:09

Bartek Banachewicz