我知道这个问题已经在网上被问过好几次了,但我找不到任何有用的答案。
enter
一旦用户按下一个键(例如或esc
),我想继续运行一个循环并打破它。我不希望它在此过程中询问用户任何输入。
我有一个while
循环。
我是 C++ 新手,所以请简单回答。
我的系统是 Mac OS X。
我知道这个问题已经在网上被问过好几次了,但我找不到任何有用的答案。
enter
一旦用户按下一个键(例如或esc
),我想继续运行一个循环并打破它。我不希望它在此过程中询问用户任何输入。
我有一个while
循环。
我是 C++ 新手,所以请简单回答。
我的系统是 Mac OS X。
你去吧。我希望这有帮助。
#include <iostream>
#include <thread>
#include <atomic>
// A flag to indicate whether a key had been pressed.
atomic_bool keyIsPressed(false);
// The function that has the loop.
void loopFunction()
{
while (!keyIsPressed) {
// Do whatever
}
}
// main
int main(int argc, const char * argv[])
{
// Create a thread for the loop.
thread loopThread = thread(loopFunction);
// Wait for user input (single character). This is OS dependent.
#ifdef _WIN32 || _WIN64
system("pause");
#else
system("read -n1");
#endif
// Set the flag with true to break the loop.
keyIsPressed = true;
// Wait for the thread to finish.
loopThread.join();
// Done.
return 0;
}
更新:由于标志keyIsPressed
在线程之间共享,我为此添加atomic
了。感谢@hyde。
这确实取决于操作系统,但很有可能您使用的是 Windows。
首先,您需要包括:
#include <Windows.h>
它使您可以访问函数 GetAsyncKeyState 和 Windows 的关键宏(Windows 的关键宏列表)。
您还需要最高位来评估按键;只需在您的代码中将其初始化为 const :
const unsigned short MSB = 0x8000;
最后,让我们将所有内容放在一个函数中:
bool listenKeyPress(short p_key)
{
//if p_key is pushed, the MSB will be set at 1
if (GetAsyncKeyState(p_key) & MSB)
{
return true;
}
else return false;
}
//Example of a call to this function to check if up enter is pressed :
listenKeyPress(VK_RETURN)
然后你的while循环可以输入:
while (!listenKeyPress(VK_ENTER))
{
}
或者
bool quit = false;
while (!quit)
{
if (listenKeyPress(VK_ENTER) || listenKeyPress(VK_ESCAPE)
quit = true;
}
给你!
开始时我很好奇自己如何做到这一点......结果从来没有真正使用过,最好只使用 getch() 但是如果你需要这个并使用 windows includeWindows.h
和下面的代码应该指向正确的方向(希望如此)
bool f = true;
while (f)
{
if (GetAsyncKeyState(VK_UP)){
//Enter code for when a button is pushed here
f = false;
}
else{
//Code to run until the button is pushed
}
}
如果您想使用不同的按钮 VK_UP 可以更改为您拥有的任何键或鼠标按钮,只需滚动列表(假设您可能是使用 Visual Studio 的学生)如果您没有列表查找适用于该按钮的键你想按。
编辑:另外,如果您希望它永远运行,请删除 f = false 并且它会在按下按钮时工作,而在不按下按钮时可以做任何您喜欢的事情(虽然不是很好的编码实践,但不会退出 while 循环,所以可能最好测试在另一个while循环中按下的键以退出)