Made a digital clock using C program : This is a simple digital clock i made and the issue i am having is that every time the time gets incremented the printf gets printed . Since i am on mac i cant use <conio.h> .
My expectation : I want the program to display a single printf and the increment happens in a single printf instead of new printf every time the time changes.
#include<stdio.h>
#include <unistd.h>
#include <stdlib.h >
int main()
{
int h, m , ;
int d=1;
printf("Enter the time : ");
scanf("%d%d%d", &h,&m,&s);
if(h>12 || m>60 || s>60){
printf("ERROR!!");
exit(0);
}
while(1){
s++;
if(s>59){
m++;
s=0;
}
if(m>59){
h++;
m=0;
}
if(h>12){
h=1;
}
printf("\n Clock ");
printf(" %02d:%02d:%02d",h, m ,s);
sleep(1);
}
return 0;
}
You need more thorough error checking on the time entered (what if the user enters negative values, or minutes or seconds equal to 60); and to get the time to print on a single line, you need to replace the
\nwith a\r, and to flushstdout.To get a clock that is more robust and with more precise timing, based on your system's real-time clock, try this:
Look at the man pages for
time,localtime, andstrftimeto see how this works, but basically it gets the time from the system clock, and if it has changed since the last time it was printed, format it and print it.