6

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

PS:我不能使用getch, cin.ignore, 或者cin.get因为它会停止循环。

4

4 回答 4

3

好吧,你想要的是异步输入。cinwait for enter提供的所有方法。您将不得不为此使用系统特定的功能,或者使用可以为您完成此操作的库。

您需要做的不仅是在 while 循环中处理您的逻辑,而且还要从您的操作系统的消息管道中侦听。如果您想了解有关该信息的更多信息,请发表评论。

编辑:还有另一种方法,但我不推荐它,因为我相信它可能是不可移植的。以下代码在VS2012RC下编译运行。

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

using namespace std;

int main()
{
   cout << "Enter a character";
   getch();
}
于 2012-08-16T13:04:50.020 回答
3

下面是一个使用kbhit()并具有无限循环的 Windows 控制台代码。但是如果键盘被击中,它会打破循环并退出。如果你有<conio.h>,试试这个:

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

using namespace std;


int main()
{


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

   }

  return 0;
}
于 2012-08-16T13:35:42.167 回答
2

C++ 中没有“键盘”。您只有一个不透明的输入数据流,您的终端偶尔会使用自己的键盘输入填充该数据流。这几乎总是一个缓冲的、可编辑的逐行输入,因此您无法知道何时按下了任何给定的键。

您需要一种特定于平台的方法来直接与较低级别的终端通信。一个这样的库,相当广泛和可移植,是ncurses(存在兼容的 Windows 变体)。SDL 和 Allegro 等便携式图形应用程序框架也提供原始键盘处理。

于 2012-08-16T13:08:35.680 回答
0

这将检查“左箭头”是否被按下:

GetKeyState(VK_LEFT)

这也不会等待任何事情。只是检查一些标志。

winuser.h 中定义的其他一些键:

#define VK_NUMPAD0        0x60
#define VK_NUMPAD1        0x61
#define VK_NUMPAD2        0x62
#define VK_NUMPAD3        0x63
#define VK_NUMPAD4        0x64
#define VK_NUMPAD5        0x65
#define VK_NUMPAD6        0x66
#define VK_NUMPAD7        0x67
#define VK_NUMPAD8        0x68
#define VK_NUMPAD9        0x69

#define VK_CLEAR          0x0C
#define VK_RETURN         0x0D

#define VK_SHIFT          0x10
#define VK_CONTROL        0x11
#define VK_MENU           0x12
#define VK_PAUSE          0x13
#define VK_CAPITAL        0x14

#define VK_KANA           0x15
#define VK_HANGEUL        0x15  /* old name - should be here for compatibility */
#define VK_HANGUL         0x15
#define VK_JUNJA          0x17
#define VK_FINAL          0x18
#define VK_HANJA          0x19
#define VK_KANJI          0x19

#define VK_ESCAPE         0x1B

#define VK_CONVERT        0x1C
#define VK_NONCONVERT     0x1D
#define VK_ACCEPT         0x1E
#define VK_MODECHANGE     0x1F

#define VK_SPACE          0x20
#define VK_PRIOR          0x21
#define VK_NEXT           0x22
#define VK_END            0x23
#define VK_HOME           0x24
#define VK_LEFT           0x25
#define VK_UP             0x26
#define VK_RIGHT          0x27
#define VK_DOWN           0x28
#define VK_SELECT         0x29
#define VK_PRINT          0x2A
#define VK_EXECUTE        0x2B
#define VK_SNAPSHOT       0x2C
#define VK_INSERT         0x2D
#define VK_DELETE         0x2E
#define VK_HELP           0x2F

winuser.h 必须包含在 windows.h 中

于 2012-08-16T13:16:14.347 回答