gpt4 book ai didi

c++ - C++ 程序应该在他按下 'esc' 时立即退出

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:25:06 26 4
gpt4 key购买 nike

我有一个程序,其中有一段代码看起来像这样:

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

我希望程序在他按下'esc' 键后立即退出。并且用户在按下 'esc' 键后不必再按下'enter' 键。那怎么办呢??

最佳答案

在 Windows 中,您可以使用 Windows API 来完成。 GetAsyncKeyState(VK_ESCAPE) 帮助您检查是否按下了 Escape。你可以尝试这样的事情:

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

我遇到了同样的问题,按照上面的方法解决了。这个问题对我帮助很大(处理思路来自接受的答案):C++ how do I terminate my programm using ESC button .该问题的答案中还提供了该问题的另一种解决方案。

这种检测 Esc 键的方法应该也可以(但是,我没有正确测试它):

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

关于c++ - C++ 程序应该在他按下 'esc' 时立即退出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20579502/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com