我怎样才能一直运行循环,直到按下键 (C++)

How can I keep running a loop until the key is pressed (C++)

本文关键字:C++ 一直 循环 运行      更新时间:2023-10-16

我知道这个问题在网上被问过好几次了,但我找不到任何有用的答案。

我想继续运行循环并在用户按下某个键后中断它(例如 enteresc)。我不希望它在此过程中向用户询问任何输入。

我有一个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循环中被按下退出)