Is there a way to determine if a key is pressed?

I am compiling and running my programs in cygwin on a windows machine. I'm fairly inexperienced in C, but I'd like to know if a key is pressed without prompting the user (like me). Below is my pseudocode with the desired features.

char ch;
while(1){
    if(KeyBeenPressed()){
    //a key has been pressed before getting here
        ch=getKeyPressed();
        if(ch=='0'){
            printf("you have pressed 0");
        }
        else{
            printf("you did't press key 0");
        }
    }

//do other stuff
} 

      

And my own attempt at solving this after searching the internet is shown below.

#include <stdio.h>
#include <conio.h>
char ch;
void main(){
    while(1){
        if(kbhit()){ //kbhit is 1 if a key has been pressed
            ch=getch();
            printf("pressed key was: %c", ch);
        }
    }
}

      

The problem with this code is that the conio.h file cannot be found (and I haven't found any other way to resolve this issue). Apparently the gcc compilers cannot handle conio.h (I linked the link to make it stand). http://www.programmingsimplified.com/c/conio.h

So I am wondering if anyone of you knows a way to determine if a key was pressed in C, I would also like to get the pressed key preferably in char (I plan to use 0-9 expression for that). The important thing is that the program cannot wait for a key press.

I am grateful for any suggestions that might resolve this! Best wishes Henrik

+1


source to share


2 answers


I am using the following function for kbhit()

. It works fine on the g ++ compiler on Ubuntu.



#include <termios.h>
#include <unistd.h>
#include <fcntl.h>
int kbhit(void)
{
  struct termios oldt, newt;
  int ch;
  int oldf;

  tcgetattr(STDIN_FILENO, &oldt);
  newt = oldt;
  newt.c_lflag &= ~(ICANON | ECHO);
  tcsetattr(STDIN_FILENO, TCSANOW, &newt);
  oldf = fcntl(STDIN_FILENO, F_GETFL, 0);
  fcntl(STDIN_FILENO, F_SETFL, oldf | O_NONBLOCK);

  ch = getchar();

  tcsetattr(STDIN_FILENO, TCSANOW, &oldt);
  fcntl(STDIN_FILENO, F_SETFL, oldf);

  if(ch != EOF)
  {
    ungetc(ch, stdin);
    return 1;
  }

  return 0;
}

      

+3


source


Most Dos, Windows 3.x, or win32 platforms provide a conio.h file, but unix or linux Os does not provide this file normally. If you are using unix or linux Os you must download it online. I hope my answer is helpful to you.



0


source







All Articles