Search code examples
ckeyterminate

stop infinite loop or process with press a specific key in c


I've just thought about the ctrl+c in the terminal which as you know stop every process, updating, an infinite loop and etc. then I start to program a code which prints the Fibonacci sequence in an infinite loop and trying to stop it with a specific key but I have no idea how it's possible.

Can anyone help me with this problem?

Thanks In advance


Solution

  • Hy man you can do something like this:

    #include <stdio.h>
    #include <conio.h>              // include the library header, not a standard library
    
    int main(void)              
    {
        int c = 0;             
        while(c != 'key that you want')             // until correct key is pressed
        {
            do {                
                //Fibonacci sequence
            } while(!kbhit());      // until a key press detected
            c = getch();            // fetch that key press
        }
        return 0;
    }