Question

I have a program in which there is a code which looks something like this:

int Element[15];
cout << "Enter name/symbol of the Element: ";
cin >> Element;

and I want the program to exit as soon as he presses 'esc' key. And also the user should not have to press the 'enter' key after pressing the 'esc' key. So how to do that??

Was it helpful?

Solution

In Windows you can do it using Windows API. GetAsyncKeyState(VK_ESCAPE) helps you to check if Escape is pressed. You can try something like this:

#include <windows.h>
#include <iostream>

using namespace std;

int main() {

  int Element[15];
  HANDLE h;

  do {  
    h = GetStdHandle(STD_INPUT_HANDLE);
    if(WaitForSingleObject(h, 0) == WAIT_OBJECT_0) {
      cout << "Enter name/symbol of the Element: ";
      cin >> Element;
    }
  } while(GetAsyncKeyState(VK_ESCAPE)==0);

  return 0;
}

I had the same problem and solved it that way above. This question helped me a lot (the handling idea is from the accepted answer): C++ how do I terminate my programm using ESC button . Another solutions for this problem are also provided in that question answer from the link.

That way of detecting Esc key should also work (however, I didn't test it properly):

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

using namespace std;

int main() {
  int c = _getcha();
  while(c != 27) {
    // do stuff
    c = _getcha();
  }

  return 0;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top