0

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

  • The ISO C standard itself standard does not know the concept of keypresses. It only knows the concept of reading input from streams. Therefore, you will require platform-specific extensions to be able to detect whether a key has been pressed. For this reason, if you want an answer to your question, you will have to specify the platform to which your question applies (for example by setting an appropriate tag). – Andreas Wenzel Nov 22 '20 at 12:39

2 Answers2

1

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;
}
Gonçalo Bastos
  • 376
  • 3
  • 16
  • 1
    Note that the functions `kbhit` and `getch` are not part of the ISO C standard, but are platform-specific extensions. For example, they will work on the Microsoft Windows platform, [but not on the Linux platform](https://stackoverflow.com/questions/8792317/where-is-the-conio-h-header-file-on-linux-why-cant-i-find-conio-h). The OP did not specify that the question applies to any specific platform. So you cannot rely on these functions being available. – Andreas Wenzel Nov 22 '20 at 12:33
  • @AndreasWenzel Yes thats true – Gonçalo Bastos Nov 22 '20 at 12:39
1

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