Time as Statement Inside If
Feb 5, 2021 at 9:11am UTC
Hello!
I would like to compare two different hours aiming print certain sentences according the current hour, nevertheless my code is always returning Sleep dear honey sugar. Could someone help see where is my mistake?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#include <iostream>
#include <iomanip>
#include <ctime>
#include <chrono>
int main() {
errno_t err;
struct tm time_info;
time_t time_create = time(NULL);
localtime_s(&time_info, &time_create);
char timebuf[26];
err = asctime_s(timebuf, 26, &time_info);
std::cout << timebuf;
if (timebuf > "5:30:30" && timebuf < "17:30:00" ) { std::cout << "Wake Up care the cows!" ; }
else std::cout << "Sleep dear honey sugar" ;
}
Last edited on Feb 5, 2021 at 9:13am UTC
Feb 5, 2021 at 10:33am UTC
You can't compare times as strings. You need to compare separately the hour, min etc. Or convert the required time to a time_t value and compare. Consider:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
#include <iostream>
#include <ctime>
int main() {
std::tm time_info;
const auto time_create {time(0)};
localtime_s(&time_info, &time_create);
if ((time_info.tm_hour > 5 || (time_info.tm_hour == 5 && time_info.tm_min > 30))
&& (time_info.tm_hour < 17 || (time_info.tm_hour == 17 && time_info.tm_min < 30)))
std::cout << "Wake Up care the cows!" ;
else
std::cout << "Sleep dear honey sugar" ;
}
Last edited on Feb 5, 2021 at 10:33am UTC
Feb 5, 2021 at 10:36am UTC
You cannot compare c strings like that. Why are you trying to compare strings at all?
In
time_info
you have all the data you need.
1 2 3
time_info.tm_sec
time_info.tm_min
time_info.tm_hour
Last edited on Feb 5, 2021 at 11:01am UTC
Feb 5, 2021 at 10:59am UTC
Thank you so much Seeplus and Coder777. I understood the working! Thank you
Topic archived. No new replies allowed.