Reputation: 83
I Have written a Fibonacci Series in C. It functions well and provide numbers more than 3e100 also.
But my question here, is, what is the user want to stop the print process in the middle and exit the loop, how to capture the users input ?
For instance, if he input that he wants first 100 numbers of the series, then changed mind and wants to exit the printing process, while its in the middle. How to do that ?
I Thought of capturing ^c
(CTRL+C) when the loop runs, but I'm unsure how to do that.
Here is my code:
printf("Welcome to Fibonacci Series Mode.\n\nEnter how many numbers do you want from the series, from the start: ");
scanf("%d", &N);
x = 0;
y = 1;
F = 3;
Numbering = 3;
printf("Here is Your Series:\n\n");
if (N == 1)
{
printf("[1] 0\n");
Sleep(1000);
}
if (N == 2)
{
printf("[1] 0\n");
Sleep(75);
printf("[2] 1\n");
Sleep(1075);
}
if (N == 3)
{
printf("[1] 0\n");
Sleep(75);
printf("[2] 1\n");
Sleep(75);
printf("[3] 1\n");
Sleep(1075);
}
if (N > 3)
{
printf("[1] 0\n");
Sleep(75);
printf("[2] 1\n");
Sleep(75);
}
while (N > 3 && F <= N)
{
xy = x + y;
printf("[%.0d] %.5g\n", Numbering, xy);
Sleep(75);
x = y;
y = xy;
F++;
Numbering++;
}
Sleep(1000);
}
That is just a portion of my whole code, which I am not including here, that's why you cannot see main()
and the header files.
Upvotes: 1
Views: 1206
Reputation: 5615
In C, IO is blocking by default. So if you want to listen to user input during the loop, you must wait for the user's input before moving on.
The solution to this is using signals. Specifically SIGINT
with CTRL + C. Now it is possible to catch this signal on your program side to do some cleanup or just anything else you want. Your concern might be to make a function for graceful exit upon receiving SIGINT
, instead of an instant exit during printing.
If you want to catch the signal, you could use this-
#include <signal.h>
void SIGINT_handler(int sig)
{
// Ignore the signal's default behaviour
signal(sig, SIG_IGN);
// Do graceful printing/cleanup here
exit(0);
}
Now you need to bind this function to SIGINT
, you can do that in main
signal(SIGINT, INThandler);
Note: This is a very simple example just to point you towards the right direction. Since you're using printf
inside your code, this will break.
Signal interception during IO is difficult to get right. What if the signal was called in the middle of a printf
call? The behavior would likely not be how you want it to be.
More information here
Upvotes: 3