The C++ program should exit as soon as he presses 'esc'

谁说我不能喝 提交于 2019-12-06 06:15:33
gthacoder

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;
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!