I decide to make clock in C as my first "Project", Changing minutes after 60 sec mark went well but when i need to change hours after minutes my secon number of seconds wont reset so it stayis with number 9 stuck until i go to the point of 10 sec.
#include<stdio.h>
#include<Windows.h>
int main ()
{
int h = 0,m = 59, s = 55;
int prekid = 1;
while (prekid == 1)
{
printf(" \r H:%d | M: %d | S: %d",h,m,s);
s ;
fflush(stdout);
if (s == 60)
{
m ;
s= 0;
}
if (m == 60)
{
m = 0;
s= 0;
h ;
}
sleep(1);
}
return 0;
}
CodePudding user response:
Reason for your issue: when line gets shorter, characters from previous, longer line remain on screen.
Solution 1, add enough spaces, 3 in this case I believe, at the end of format string to overwrite extra numbers:
printf(" \r H:%d | M: %d | S: %d ",h,m,s);
Solution 2, write fixed width output, here with leading zeroes:
printf(" \r H:d | M: d | S: d",h,m,s);
CodePudding user response:
Rathe than print a variable width of text (and leave lefts-overs that caused OP's troubles), print a fixed width:
// printf(" \r H:%d | M: %d | S: %d",h,m,s);
printf("\r H:- | M:- | S:-", h, m, s);
"-"
directs printf()
to print at least 2 characters, padding on the left with spaces as needed.