I have to write a program that takes two different inputs (lets call them FirstTime & SecondTime) and then convert the two times to seconds , get the difference and display the result back into 24hour format, input must be (HH MM SS, i have this part correct) and then output must be (HH:MM:SS). Also the program must check which time is smaller before subtracting and i have to use assert macro to verify the times are legitimate times ((i Know this is something like assert (FirstTime >= 00 00 00 && FirstTime <= 23 59 59)) but it doesnt allow me to use >= and <= as it is still an integer
cout << "Please enter the first time in a 24hour format (eg hh mm ss): ";
getline (cin, FirstTime);
assert (FirstTime >= 00 00 00 && FirstTime <= 23 59 59);
cout << "Please enter the second time in a 24hour formant (eg hh mm ss): ";
getline (cin, SecondTime);
assert (SecondTime >= 00 00 00 && SecondTime <= 23 59 59);
return 0;
}
#include <iostream>
#include <cassert>
usingnamespace std;
int main()
{
int h1, m1, s1, h2, m2, s2;
cout << "Enter first time in the format hh mm ss: ";
cin >> h1 >> m1 >> s1;
cout << "Enter second time in the format hh mm ss: ";
cin >> h2 >> m2 >> s2;
// check if times are valid
assert((h1 >= 0) && (m1 >= 0) && (s1 >= 0));
// do the same for 2. time
}
that actually makes it alot easier, i have been trying to get it to work with the string for almost 2 hours now.
So my next question is to convert it to seconds, i am going to assume i would make a new int for the first time and the second time as well as to get the difference
then i would say
FirstTime = (h1 * (60*60)) + (m1 * 60) + s1 to convert the first time into seconds and then the same for SecondTime, and then use a if function to check which one is smaller and then continue the subtraction but how do i convert the difference back to a 24h format which displays HH:MM:SS
how do i convert the difference back to a 24h format which displays HH:MM:SS
Using integer division (/) and modulus (%).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#include <iostream>
int main()
{
int secs_hour { 60 * 60 };
int secs_minute { 60 };
// hours minutes seconds
int time { (5 * secs_hour) + (15 * secs_minute) + 27 };
int hours { time / secs_hour };
// minutes and seconds are still "encoded" as a remainder
int seconds { time % secs_hour };
std::cout << "Hours: " << hours << '\n';
// calculate for the minutes, seconds is the remainder
}
You could also use regular expressions <regex> for this, but given that it is quite simple, it would be best to save regex for more complex string parsing.