Jump to content
  • Advertisement
Sign in to follow this  
Kheyas

C++ Button Press Detection

This topic is 2475 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hello!
How can I detect if an user pressed a button instead of getting him to type it/enter it.
Example:

printf("Choose an option");
printf("1.Eat");
printf("2.Sleep");

//get button press
if (buttonpress ==1) Eat();
if (buttonpress ==2) Sleep();

Instead of: scanf("%d",&choise); if(choise==1)Eat();

You can modify the code as you wish. I just need to understand the part of the code where you get the button. IF POSSIBLE.

Share this post


Link to post
Share on other sites
Advertisement
In Windows, generally you'd use getch(), defined in <conio.h>; in Linux, you'd use a function like this (I can't remember which headers are required):


#include <stdio.h>
#include <sys/select.h>
#include <termios.h>
#include <stropts.h>
#include <unistd.h>

char getch(void){
struct termios oldt,newt;
char ch;
tcgetattr( STDIN_FILENO, &oldt );
newt = oldt;
newt.c_lflag &= ~( ICANON | ECHO );
tcsetattr( STDIN_FILENO, TCSANOW, &newt );
scanf (" %c", &ch);
tcsetattr( STDIN_FILENO, TCSANOW, &oldt );
return ch;
}


Other than that, getting a certain character without requiring the user to press Return is pretty platform specific, and you will need to research methods for your OS/window manager.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!