Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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;
}
like image 839
pandoragami Avatar asked Apr 01 '13 04:04

pandoragami


1 Answers

#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;
}
like image 114
Nasir Mahmood Avatar answered Oct 29 '22 07:10

Nasir Mahmood