按ESC键退出while循环【C/C++】

在使用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>

using namespace std;

int main(int argc, char* argv[])
{
    while (true)
    {
        if (GetKeyState(VK_ESCAPE)) // 按ESC退出
            break;
        cout << "1" << endl;
    }
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/cvwyh/p/10384983.html