C++ 如何在按下键(C+;+;)之前一直运行循环
我知道这个问题在网上已经被问过好几次了,但是我找不到任何有帮助的答案 我希望继续运行循环,并在用户按下某个键(例如,C++ 如何在按下键(C+;+;)之前一直运行循环,c++,macos,console-application,keyboard-input,C++,Macos,Console Application,Keyboard Input,我知道这个问题在网上已经被问过好几次了,但是我找不到任何有帮助的答案 我希望继续运行循环,并在用户按下某个键(例如,enter或esc)后将其中断。我不希望它在这个过程中询问用户任何输入 我有一个while循环 我的系统是Mac OS X。好了。我希望这有帮助 #include <iostream> #include <thread> #include <atomic> // A flag to indicate whether a key had bee
enter
或esc
)后将其中断。我不希望它在这个过程中询问用户任何输入
我有一个while
循环
<我是C++新手,请简单回答。< /P>
我的系统是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;
}
#包括
#包括
#包括
//指示是否按下某个键的标志。
原子布尔键已按下(假);
//具有循环的函数。
void loopFunction()
{
而(!keyipressed){
//做任何事
}
}
//主要
int main(int argc,const char*argv[]
{
//为循环创建一个线程。
线程loopThread=线程(loopFunction);
//等待用户输入(单个字符)。这取决于操作系统。
#ifdef|u WIN32 | | u WIN64
系统(“暂停”);
#否则
系统(“读取n1”);
#恩迪夫
//将标志设置为true以中断循环。
keyipressed=true;
//等待线程完成。
loopThread.join();
//完成了。
返回0;
}
更新:由于标记
keyipressed
在线程之间共享,我为此添加了atomic
。多亏了@hyde.这确实取决于操作系统,但很可能是您使用Windows
首先,您需要包括:
#include <Windows.h>
最后,让我们将所有内容放在一个函数中:
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))
{
}
或
好了 开始时,我很好奇如何做到这一点。。。事实证明从未真正使用过,最好只使用getch(),但如果您需要此功能并使用windows include
windows.h
,下面的代码将为您指明正确的方向(希望如此)
如果您想使用不同的按钮,VK_UP可以更改为您拥有的任何键或鼠标按钮,只需滚动列表(假设您可能是使用visual studio的学生)如果没有列表,请查找适用于您想要按下的按钮的键
编辑:如果您希望它永远运行,请删除f=false,它将在按下按钮和不按下按钮的情况下工作,以执行任何您喜欢的操作(不需要很好的编码实践来保持while循环不退出,但最好在另一个while循环中测试一个键是否被按下以退出)从命令行运行时,用户可以按ctrl+C结束一个程序。您已经尝试过什么?@Crazyman135790:这些信息如何改善这个问题?类似这样的信息取决于操作系统。@hyde我使用的是Mac OS X和Xcode。您可以使用fgetc(stdin)来制定这个标准。。。使用
system()
暂停?为什么不getchar()
或std::cin
?您还应该注意,这是C++11,所以OP需要使用-std=C++11标记。您是对的。它也会起作用。但是,getchar
和std::cin
需要enter
按键。其他人不会。只要用户按下任何键,它们就会继续。以防万一。至少把键按成一个原子键。否则,优化或多个CPU或诸如此类的操作可能会阻止其他线程看到其值的变化。
while (!listenKeyPress(VK_ENTER))
{
}
bool quit = false;
while (!quit)
{
if (listenKeyPress(VK_ENTER) || listenKeyPress(VK_ESCAPE)
quit = true;
}
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
}
}