In: Computer Science
Write this program in C++ language. Use the concept of structures. DO NOT use vectors.
Q (4) Create a structure called time. Its three members, all
type int, should be called hours,
minutes, and seconds. Write a program that prompts the user to
enter a time value in hours,
minutes, and seconds. This should be in 12:59:59 format. This
entire input should be assigned
first to a string variable. Then the string should be tokenized
thereby assigning the 1st token
to hours, 2nd token to minutes, and 3rd token to seconds member
variables of the structure
called time. Finally inside a void Print_in_Seconds(void) member
function of time structure,
it should print out the total number of seconds represented by this
time value:
long totalsecs = t1.hours*3600 + t1.minutes*60 + t1.seconds (10
Points)
Program Code [C++]
#include <iostream>
#include <sstream>
using namespace std;
// time struct
struct time {
// All Required members for hours, minutes and seconds
int hours;
int minutes;
int seconds;
// member function Print_in_Seconds
void Print_in_Seconds() {
// A variable of long type which will store total seconds as mentioned in question
// this is a pointer which refers to the member variables of the C++ struct or class
// So we can use this to access every member of time struct
// Below we are accessing hours, minutes and seconds of time struct using this and adding them
// Then returning the total seconds
long totalsecs = this->hours * 3600 + this->minutes * 60 + this->seconds;
cout << "Total number of seconds: " << totalsecs << endl;
}
};
int main() {
struct time t1;
// Asking user to enter a tome
cout << "Enter a time value in hours, minutes and seconds: ";
string timeVal;
cin >> timeVal; // Taking input as a string
// Tokenizing string three times to get value of hours
stringstream t(timeVal); // We'll tokenize using stringstream of c++
string temp; // An extra variable to store tokenized string
getline(t, temp, ':'); // First getting hours ex: 12:59:59 -> temp will have 12
t1.hours = stoi(temp); // Now since it is a string, we need to convert to int as hours member of struct time and storing in t1 object
getline(t, temp, ':'); // Now getting minutes ex: 12:59:59 -> temp will now have 59
t1.minutes = stoi(temp); // stoi(string to int conversion) again converting to string & storing in t1's minutes
getline(t, temp, ':'); // Now getting seconds => temp will have 59 in case of 12:59:59
t1.seconds = stoi(temp); // Converting again to int
// Now printing time on console
cout << "time is " << t1.hours << ":" << t1.minutes << ":" << t1.seconds << endl;
t1.Print_in_Seconds(); // Calling Print_in_Seconds function to show total seconds on console
return 0;
}
Sample Output:-
----------------------------------------------------------------------
COMMENT DOWN FOR ANY QUERIES!!!
HIT A THUMBS UP IF YOU DO LIKE IT!!!