C++: execute a while loop until a key is pressed e.g. Esc?

pandoragami picture pandoragami · Apr 1, 2013 · Viewed 47.4k times · Source

Does anyone have a snippet of code that doesn't use windows.h to check for a key press within a while loop. Basically this code but without having to use windows.h to do it. I want to use it on Linux and 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;
}

Answer

Nasir Mahmood picture Nasir Mahmood · Apr 1, 2013
#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;
}