我怎样才能一直运行循环,直到按下键 (C++)
How can I keep running a loop until the key is pressed (C++)
我知道这个问题在网上被问过好几次了,但我找不到任何有用的答案。
我想继续运行循环并在用户按下某个键后中断它(例如 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 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 包含Windows.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循环中被按下退出)
相关文章:
- 即使我读取了所有内容,在FIFO上打开的QSocketNotifier也会一直启动
- Switch 语句(字符串)一直选择默认值,除非其为零
- 链接 c++ 动态库一直失败
- 我试图用这段代码找到二叉树的高度,但它一直返回 0,有人可以告诉我为什么吗?
- 我正在尝试创建一个菜单,但我的代码一直在循环
- 我想在 c++ 中对单向链表进行冒泡排序,但我一直面临左值错误,无法解决它
- 我一直试图弄清楚我在这个链表程序中做错了什么
- 我正在尝试在 C++ 中做一个方程,但它一直输出 1
- 工作线程一直在等待,condition_variable甚至调用了notify_all
- 我一直得到'std::invalid_argument'什么():似乎无缘无故地抛出 stoi 异常?
- 我无法让我的程序工作,我一直得到未定义的符号:C
- 我一直收到错误"cannot convert 'float*' to 'float' in return"
- 我需要帮助创建一个评分系统,但它一直给我一个错误,注释掉的整数是给我带来麻烦的部分
- 选择"Y"继续后,我的程序一直处于关闭状态
- 为什么这一直打印圆的宽度?
- 如何找出为什么我的程序一直有一个无限循环?
- Ofstream一直给我函数的最后一行,而不是显示所有内容
- Winapi可以一直使用并且可以在所有版本的Windows上运行吗?
- C++ libssh - ssh_channel_read() 一直返回 0,ssh_channel_is_open()
- 我是 c++ 编程的新手,我一直在做以下任务: