Digital Clock Program in C++
Source Code:
// header file for drawing graphic objects
#include<graphics.h>
//header file to get system time
#include <ctime>
int main( ){
// initializing graphic window in C++
initwindow( 900 , 400 , "C++ Digital Clock");
// Specifying Text style
settextstyle(4, HORIZ_DIR, 7);
outtextxy(10,10,"Digital Clock");
settextstyle(3, HORIZ_DIR, 10);
char bfHrs[10]; // used to copy hours
char bfMin[10]; // used to copy minutes
char bfSec[10]; // used to copy seconds
int hrs;
// !kbhit means loop until any key pressed
while(!kbhit()) {
// Getting System Time
time_t now = time(0);
tm *ltm = localtime(&now);
/* Condition for converting 24
hours to 12 hours clock */
if(ltm->tm_hour > 12) {
hrs = ltm->tm_hour - 12;
} else {
hrs = ltm->tm_hour;
}
//copying hours to char buffer
sprintf(bfHrs, "%d", hrs);
//copying minutes to char buffer
sprintf(bfMin, "%d", ltm->tm_min);
//copying seconds to char buffer
sprintf(bfSec, "%d", ltm->tm_sec);
outtextxy(100,100, bfHrs );
outtextxy(250,100, ":" );
outtextxy(350,100, bfMin );
// delay for showing blinking second separator
delay(200);
outtextxy(500,100, ":" );
outtextxy(600,100, bfSec );
delay(800);
outtextxy(500,100, " " );
}
getch();
// Closing graphic console
closegraph();
return 0;
}
Output:
Working:
In this program example we have included two header files.
- graphics.h
- ctime
First header file is used to display graphiic objects such as circle, rectangle and text in graphic mode. For this purpose first of all we initiate a graphic window using initwindow function. Initwindow function is defined in graphics.h header file. This function take three parameters, which are width, height and title of the graphic window. First two parameters are of integer type and third parameter is of string type(Windows Title).
After window initialization we get system time using time() method. In this example we provide 0 (zero) as parameter to the time function. We can also provide NULL as parameter. This time function will return us time in 24 hours format. After getting time we place here an if else condition that will used to convert 24 hours into 12 hours time format.
Outtextxy function is used to display text in graphics mode. This function take x and y coordinate and third parameter as char array (array of characters as string). So that to display numbers (Such as hours, minutes and seconds) using outtextxy function we must convert these integer values into char array format.
Sprintf function is used to store integer into char array buffer, so that it can be displayed using outtextxy function.
The final part of this program is to write down an infinite loop that will get and display updated time in graphics mode. For this purpose we have used here while loop statement. In while loop we have write down !kbhit() function as condition. Which means that this loop will execute statements of its body until user does not press any key from keyboard. kbhit in C++ header file stands for keyboard hit.