Reputation: 266
I'm trying to create simple program that requests a user to input a number but in the upper section I display a clock that updates every second.
Here's what I know
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
int a;
int main(void) {
int a =1;
while(a)
{
system("cls");
time_t rawtime;
struct tm* time_;
time(&rawtime);
time_ = localtime(&rawtime);
printf("%i:%i:%i %i %i %i\n", time_->tm_hour, time_->tm_min,
time_->tm_sec, time_->tm_mday, time_->tm_mon+1,
time_->tm_year+1900);
printf("Give the input :");
scanf("%d",&a);
}
return 0;
}
I took the printing time code from Program a simple clock in C
What my code does is print the time and then it waits for the input, but it doesn't update the clock until I give the input.
Is there any possible way to do what I want or what keyword do I needed to search the solution? I'm sorry if my English broken, but if what I say isn't clear enough just run the code :).
Upvotes: 1
Views: 1713
Reputation: 148910
There are only two ways to display something while waiting for input:
TL/DR: Even if it looks simple (and was indeed possible with basic language in the 80' on any personnal computer), non blocking terminal IO is far from simple in C language because of the assumption that the terminal is just a special case of IO.
Upvotes: 1
Reputation: 1663
What you want is "non-blocking I/O".
How do you do non-blocking console I/O on Linux in C?
There is an answer in the above linked question that has a code snippet. The accepted answer also states that:
you pretty much don't do non-blocking I/O
and if you have to, you will
simplify this another way, by putting the console I/O into a thread or lightweight process.
The code snipped is hideously complicated and in my experience not guaranteed to work.
Upvotes: 0
Reputation: 1369
Your problem is simple: you can't wait for an user input and do something else meanwhile, unless you use threads. May be what you could do is to wait for an input for a certain amount of time, print time and loop.
Otherwise, just know that using thread is not really complicated, but it will increase significantly the complexity of your program which purpose seemed to remain simple.
Upvotes: 0