0

I am new to c programming I am working on a code which requires the program to keep running until i hit a specific key(not with enter but with just one button)

For example-

My code keeps on printing "Hello World"

Hello world
Hello world
Hello world
Hello world
Hello world
.
.
.

As soon as i press a button say the letter A then the program should stop.

I tried using getch(); But it will pause the code until i hit a character and then goes to the next line. How do i overcome this. Can someone please help.

Naveen
  • 1,441
  • 2
  • 16
  • 41
  • read about [ncurses](https://www.gnu.org/software/ncurses/ncurses.html) library – pmg Sep 22 '19 at 10:16

1 Answers1

1

Try to use GetKeyState() from winuser.h. Here's a [link][1] to help you understand.

Though you shouldn't be dealing with key presses in the console.

EDIT:

'GetKeyState()' only works with the WIN32 API.

Use getch. A demonstation below-

#include <conio.h>
#include <string.h>
#include <stdlib.h>
#include <dirent.h>
#include <math.h>
#include <time.h>
#include <stdbool.h>
#include <clib.h>//sorry for the long list of headers(I was originally using this code for some big project)
char q;
int main(int argc, char *argv[]){
    printf("enter value-");
    while(1){
if(kbhit()){

q=getch();
if(int(q)==115){  //I'm using 's' for the keypress

    printf("\nSuccess");

}
else{

    printf("\nYou didn't press s");

}
}



    }

















while(!kbhit()); //pauses console
return 0;

}```




Icelain17l
  • 11
  • 2
  • I tried this. But since i am using Ubuntu , my gcc cannot find conio.h , kbhit(). This is why i tried using curses.h and getch() but am unable to figure out a solution. Can you help me using curses.h library? – Sai Akarsh Sep 23 '19 at 06:56