Hello, OnlineGDB Q&A section lets you put your programming query to fellow community users. Asking a solution for whole assignment is strictly not allowed. You may ask for help where you are stuck. Try to add as much information as possible so that fellow users can know about your problem statement easily.

How do i detect a key being pressed in c++ / cpp

+1 vote
asked Feb 8 by SAI MERCED PENA (140 points)
i am attempting to make a game and i would like to know how to detect a key being pressed , since i normally use cin>> and have to press the enter-key, instead i want to just press a key and have something happen.

2 Answers

0 votes
answered Feb 22 by Peter Minarik (58,020 points)

For Unix/Linux, have a look at this.

For Windows, this will help.

Note: OnlineGDB runs on a Unix/Linux based server.

0 votes
answered Mar 26 by 5CMC (140 points)
Use this.

#include <termios.h>
#include <stdio.h>

#include <iostream>

int dectkey_()
{
int in;
struct termios new_settings;
struct termios stored_settings;
tcgetattr(0,&stored_settings);
new_settings = stored_settings;
new_settings.c_lflag &= (~ICANON);
new_settings.c_cc[VTIME] = 0;
tcgetattr(0,&stored_settings);
new_settings.c_cc[VMIN] = 1;
tcsetattr(0,TCSANOW,&new_settings);
 
in = getchar();
 
tcsetattr(0,TCSANOW,&stored_settings);
return in;
}

int Detectkey(){
    std::cout << "\033[s";
    int rett = dectkey_();
    std::cout << "\033[u\033[K";
    return rett;
    
}

//use Detectkey.
Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and and receive answers from other members of the community.
...