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

白昼怎懂夜的黑 提交于 2019-12-07 22:24:04

问题


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??


回答1:


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;
}


来源:https://stackoverflow.com/questions/20579502/the-c-program-should-exit-as-soon-as-he-presses-esc

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