欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

ESC键用于退出C/C++中的while循环

最编程 2024-08-11 21:20:31
...
12.23 源创会 · 上海站,聊聊 LLM 基础设施

在使用while循环时,常需要设置退出条件,常用的有按‘Q’、‘ESC’等键退出,这里列出几种退出while循环的方式:

Method1

该种方法,_getch()会一直等待键盘输入,才会执行while循环,即按一下键(ESC以外的键),执行一次。

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

using namespace std;

int main(int argc, char* argv[])
{
    while (_getch()!= 27) // 按ESC退出
    {

        cout << "1" << endl;

    }
    return 0;
}

Method2

该方法可设置while循环条件未true,GetKeyState直接检测按键值,参数为预定义的ASCII码。

#include <iostream>
#include <conio.h>
#include <winsock.h>
#include <WinUser.h>
#define KEYDOWN( vk ) ( 0x8000 & ::GetAsyncKeyState( vk ) ) // 或GetKeyState(vk) using namespace std; int main(int argc, char* argv[]) { while (true) { if (KEYDOWN(VK_ESCAPE)) // 按ESC退出 break; cout << "1" << endl; } return 0; }

 

推荐阅读