C ++ cin按键事件 [英] C++ cin keypress event

查看:111
本文介绍了C ++ cin按键事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我相信这是一个非常简单的问题,但是我找不到一个简单的答案.我有一个无限循环,例如while(1)for(;;),我需要在按键上从循环中退出.最简单的方法是什么?

I believe this is a very simple question, but I can't find a simple answer to it. I have an infinite loop, e.g. while(1), for(;;), and I need to break from the loop on a keypress. What is the easiest way to do this?

PS:我不能使用getchcin.ignorecin.get,因为它会停止循环.

P.S.: I can't use getch, cin.ignore, or cin.get because it stops the loop.

推荐答案

下面是使用kbhit()并具有无限循环的Windows控制台代码. 但是,如果敲击键盘,则会中断循环并退出. 如果您有<conio.h>,请尝试以下方法:

Below is a Windows console code that uses kbhit() and has an infinite loop. But if keyboard is hit, it breaks the loop and exits. If you have <conio.h> , try this :

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

using namespace std;


int main()
{


   while (1)
   { 
     if (kbhit()) break;

   }

  return 0;
}

这篇关于C ++ cin按键事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆