Tag Archives: One

C++ || Struct – Add One Second To The Clock Using A Struct

Here is another actual homework assignment which was presented in an intro to programming class. This program utilizes a struct, which is very similar to the class concept. For this assignment, the class was asked to make a program which prompted the user to enter a time in HH:MM:SS (Hours:Minutes:Seconds) format. Upon obtaining the time from the user, our class was asked to use a struct implementation which was to simply add one second to the time that was entered by the user. Seems easy enough, though I initially had afew problems when starting the program.

This page will be very brief in its breakdown of the program’s code, as it is already heavily commented. The code is basically unchanged from the code which was turned in for grading.

REQUIRED KNOWLEDGE FOR THIS PROGRAM

Functions
Passing a Value By Reference
Structures
Constant Variables
Boolean Expressions
Setw

NOTE: On some compilers, you may have to add #include < cstdlib> in order for the code to compile.


QUICK NOTES:
The highlighted lines are sections of interest to look out for.

STRUCT
The structure declaration is placed above the main function, as noted on lines 16-21, containing the 3 variables (Hrs, min, sec) which are defined within the program. Line 39 displays how to access those variables from the main function, having the variable “Time userTime” as the means of access. Note, line 43, the variables can utilize cin for input.

CONST
Lines 25-27 declare the constant variables, which hold the maximum allowable time the clock is able to display. The function IsTimeValid (line 72) checks to see if user defined input is within the maximum allowable limit or not.

FILL
The program will automatically display 2 numbers for hours,mins,sec even if the user only inputted one number, as noted on lines 169-172. This is basically the same as the setfill function.

Once compiling the above code, you should receive this as your output
Note: The code was compiled five separate times to display the different outputs its able to produce

==== SAMPLE RUN #1 ====
Please enter the time in HH:MM:SS format: 0:0:25
The incremented time is 00:00:26

==== SAMPLE RUN #2 ====
Please enter the time in HH:MM:SS format: 23:58:59
The incremented time is 23:59:00

==== SAMPLE RUN #3 ====
Please enter the time in HH:MM:SS format: 23:59:59
The incremented time is 00:00:00

==== SAMPLE RUN #4 ====
Please enter the time in HH:MM:SS format: : :
The incremented time is 00:00:01

==== SAMPLE RUN #5 ====
Please enter the time in HH:MM:SS format: 76:09:67
Invalid input...