在使用while循环时,常需要设置退出条件,常用的有按‘Q’、‘ESC’等键退出,这里列出几种退出while循环的方式:
Method1
该种方法,_getch()会一直等待键盘输入,才会执行while循环,即按一下键(ESC以外的键),执行一次。
#include
#include
using namespace std;
int main(int argc, char* argv[])
{
while (_getch()!= 27) // 按ESC退出
{
cout << "1" << endl;
}
return 0;
}
Method2
该方法可设置while循环条件未true,GetKeyState直接检测按键值,参数为预定义的ASCII码。
#include
#include
#include
#include
using namespace std;
int main(int argc, char* argv[])
{
while (true)
{
if (GetKeyState(VK_ESCAPE)) // 按ESC退出
break;
cout << "1" << endl;
}
return 0;
}
标签:int,C++,while,循环,ESC,退出,include
来源: https://www.cnblogs.com/cvwyh/p/10384983.html