I'm trying to make a simple clock using c. I want the values of the numbers to change alone without having to print the whole statement forever.
Output I'm looking for:
Hour => {A changing number}
Minute => {A changing number}
Second => {A changing number}
I tried this:
#include <stdio.h>
int clock(int h,int m,int s){
if(h<=60 && m<=60 && s<=60){
while(1){
s ;
if(s>60){
m ;
s = 0;
}
if(m>60){
h ;
m=0;
}
printf("Hour => %d\nMinute => %d\nSecond => %d\n",h,m,s);
}
}
return 0;
}
int main(){
int h,m,s;
printf("Enter an hour: \n");
scanf("%d", &h);
printf("Enter an minutes: \n");
scanf("%d", &m);
printf("Enter an seconds: \n");
scanf("%d", &s);
clock(h,m,s);
return 0;
}
Note: I'm a new computer science student and I'm new to c too so forgive me if I have some mistakes or methods that are not productive in my code.
CodePudding user response:
If you are willing to print the time on a single line instead of 3 lines, you can try like:
int my_clock(int h,int m,int s)
{
if(h<=60 && m<=60 && s<=60)
{
while(1)
{
s ;
if(s>60)
{
m ;
s = 0;
}
if(m>60)
{
h ;
m=0;
}
// Go to start of current line
printf("\r");
// Overwrite all
printf(" ");
// Go to start of current line
printf("\r");
// Print the new time
printf("Hour => %d Minute => %d Second => %d ",h,m,s);
fflush(stdout);
// Wait 1 sec
sleep(1);
}
}
return 0;
}
I'm however not sure all terminals will support the \r
as "Go to start of current line"