0

I want to write simple function that allows me to stop my console program by pressing any key,while the whole program works in the 'background'

Decided to use termios.h because I had some problems with lncurses.h .I finished my function and it works kinda well but I have problem to stop it by pressing any key.

int main()
{
  int key;
  for (;;) {
    key = getkey(); 

    if (key !='\0') {
      //also tried if (key != NULL) and if (key != 0x00)
      break;

    }else {

      //do some stuff in loop till any key is pressed       
    }
  }
  return 0;
}

So far I can stop program by pressing any earlier declared key,for instance

if (key =='q' || key =='w').

I know I can declared every key and in that way make it work,but im sure there is better way to do that.Thanks

bruno
  • 32,421
  • 7
  • 25
  • 37
Magor
  • 1
  • 1

2 Answers2

1

Character data is represented in a computer by using standardized numeric codes which have been developed. The most widely accepted code is called the American Standard Code for Information Interchange ( ASCII). The ASCII code associates an integer value for each symbol in the character set, such as letters, digits, punctuation marks, special characters, and control characters.

you can check the inter character is between 'a' and 'z':

if ((key >= 'a' && key <= 'z') || (key >= 'A' && key <= 'Z')){
   //stop 
}

can use this code:

#include <termios.h>
#include <stdlib.h>

void RestoreKeyboardBlocking(struct termios *initial_settings)
{
    tcsetattr(0, TCSANOW, initial_settings);
}

void SetKeyboardNonBlock(struct termios *initial_settings)
{

    struct termios new_settings;
    tcgetattr(0,initial_settings);

    new_settings = initial_settings;
    new_settings.c_lflag &= ~ICANON;
    new_settings.c_lflag &= ~ECHO;
    new_settings.c_lflag &= ~ISIG;
    new_settings.c_cc[VMIN] = 0;
    new_settings.c_cc[VTIME] = 0;

    tcsetattr(0, TCSANOW, &new_settings);
}

int main()
{
    struct termios term_settings;
    char c = 0;

    SetKeyboardNonBlock(&term_settings);

    while(1)
    {
        c = getchar();
        if(c > 0){
            //printf("Read: %c\n", c);
            //do some stuff in loop till any key is pressed       
        }

    //Not restoring the keyboard settings causes the input from the terminal to not work right
    RestoreKeyboardBlocking(&term_settings);

    return 0;
}
amin saffar
  • 1,953
  • 3
  • 22
  • 34
0

The kbhit() function in conio.h can do the job.

Let us give an example.

The following code prints natural numbers without stop or control over it

#include<stdio.h>
int main(){
    for (int k=1;;k++){
        printf("%d\n",k);
    }
}

now if we add if(kbhit())break; inside the loop, that will do the job for us

#include<conio.h>
#include<stdio.h>
int main(){
    for (int k=1;;k++){
        printf("%d\n",k);
        if(kbhit())break;
    }
}
Mostafa Ayaz
  • 480
  • 1
  • 7
  • 16