user13477968
user13477968

Reputation:

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

Upvotes: 0

Views: 214

Answers (2)

Milo Heinrich
Milo Heinrich

Reputation: 11

Using a do while works, but you can also use a boolean to stop the while loop.

#include <whateverHeaderYouUseToProcessInput.h>
#include <stdbool.h>

int main(void)
{
    bool running = true;

    while (running)
    {
        if (CheckIfKeyPressed(key))
             running = false;
    }

    return 0;
}

Upvotes: 1

Gon&#231;alo Bastos
Gon&#231;alo Bastos

Reputation: 421

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;
}

Upvotes: 1

Related Questions