C ++: execute a while loop until a key is pressed, e.g. Esc?

Does anyone have a piece of code that does not use windows.h to check for keystrokes inside a while loop. Basically this code, but without using windows.h for this. I want to use it on Linux and Windows.

 #include <windows.h> #include <iostream> int main() { bool exit = false; while(exit == false) { if (GetAsyncKeyState(VK_ESCAPE)) { exit = true; } std::cout<<"press esc to exit! "<<std::endl; } std::cout<<"exited: "<<std::endl; return 0; } 
+4
source share
5 answers

It is best to create a custom GetAsyncKeyState function that will use #IFDEF for Windows and Linux to select the appropriate GetAsyncKeyState () or equivalent.

There is no other way to achieve the desired result, the cin approach has its own problems - for example, the application should be in focus.

+2
source
 #include <conio.h> #include <iostream> int main() { char c; std::cout<<"press esc to exit! "<<std::endl; while(true) { c=getch(); if (c==27) break; } std::cout<<"exited: "<<std::endl; return 0; } 
+4
source
 char c; while (cin >> c) { ... } 

ctrl-D completes the above loop. It will continue until char is entered.

+2
source

// simplest.

  #include <iostream> #include <conio.h> using namespace std; int main() { char ch; bool loop=false; while(loop==false) { cout<<"press escape to end loop"<<endl; ch=getch(); if(ch==27) loop=true; } cout<<"loop terminated"<<endl; return 0; } 
0
source
 //its not the best but it works #include <vector> #define WINVER 0x0500 #include <windows.h> #include <conio.h> #include <iostream> int main() { char c; std::cout<<"press esc to exit! "<<std::endl; while(true) { std::cout<<"executing code! , if code stops press any key to continue or esc to stop"<<std::endl; INPUT ip; // Set up a generic keyboard event.aa ip.type = INPUT_KEYBOARD; ip.ki.wScan = 0; // hardware scan code for key ip.ki.time = 0; ip.ki.dwExtraInfo = 0; int lol = 65; //a key // Press the "A" key ip.ki.wVk = lol; // virtual-key code for the "a" key ip.ki.dwFlags = 0; // 0 for key press SendInput(1, &ip, sizeof(INPUT)); // Release the "A" key ip.ki.dwFlags = KEYEVENTF_KEYUP; // KEYEVENTF_KEYUP for key release SendInput(1, &ip, sizeof(INPUT)); c=getch(); if (c==27) break; } std::cout<<"exited: "<<std::endl; return 0; } 
-1
source

All Articles