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

 

相关文章:

  • 2022-01-07
  • 2021-04-06
  • 2022-12-23
  • 2021-08-24
  • 2021-10-08
  • 2021-07-22
  • 2022-12-23
  • 2021-06-04
猜你喜欢
  • 2022-12-23
  • 2021-07-20
  • 2022-12-23
  • 2021-11-17
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案