C++:执行while循环直到按下一个键,例如Esc?

pan*_*ami 7 c++ multiplatform exit onkeypress while-loop

有没有人有一段代码,不windows.h用于在while循环中检查按键.基本上这个代码,但不必使用windows.h它.我想在Linux和Windows上使用它.

#include <windows.h>
#include <iostream>

int main()
{
    bool exit = false;

    while(exit == false)
    {
        if (GetAsyncKeyState(VK_ESCAPE))
        {
            exit = true;
        }
        std::cout<<"press esc to exit! "<<std::endl;
    }

    std::cout<<"exited: "<<std::endl;

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

Nas*_*ood 5

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

int main()
{
    char c;
    std::cout<<"press esc to exit! "<<std::endl;
    while(true)
    {
        c=getch();
        if (c==27)
          break;
    }

    std::cout<<"exited: "<<std::endl;

    return 0;
}
Run Code Online (Sandbox Code Playgroud)


小智 2

最好的选择是创建一个自定义的“GetAsyncKeyState”函数,该函数将使用 Windows 和 Linux 的 #IFDEF 来选择适当的 GetAsyncKeyState() 或等效函数。

没有其他方法可以实现所需的结果,cin 方法有其问题 - 例如应用程序必须处于焦点。