I am studying a program that continuously updates the time and I have some questions on how it works.
When I comment out the while(1) loop, the program still runs but does not print the time. Why is the while loop needed? Isn't it a bad idea to make a while loop that always proceeds? Does the continuous while loop run the if loop every second?
From the line that stores total seconds to time(0), what data type is time(0)? Is it an int? If so, why is it followed by (0)? If I change the 0 to a 1, the following error appears:
C:\Users\Roman Justice\Desktop\Clock_1.cpp In function 'int main()':
C:\Users\Roman Justice\Desktop\Clock_1.cpp [Error] invalid conversion from 'int' to 'time_t* {aka long long int*}' [-fpermissive]
Is this error saying that time_t total_seconds is being converted to long long int?
What is the meaning of the line that reads "seconds=ct->tm_sec;"? Does this convert a part of struct time to a readable or printable format?
For the if statement, I am confused by the lines "sec_prev=seconds;" and "seconds==sec_prev+1". The first line assigns sec_prev to seconds, so does that mean they will always be the same? In the cout statement, why are the times coded as ("hours<10?"0":"") and not just "hours"?
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
int main()
{
int sec_prev=0;
while(0)
{
int seconds, minutes, hours;
string str;
//storing total seconds
time_t total_seconds=time(0);
//getting values of seconds, minutes, hours
struct tm* ct=localtime (&total_seconds);
seconds=ct->tm_sec;
minutes=ct->tm_min;
hours=ct->tm_hour;
//converting it into 12 hour format
if (hours>=12)
str="PM";
else
str="AM";
hours=hours>12?hours-12:hours;
//printing the result
if(seconds==sec_prev+1 || (sec_prev==59 && seconds==0))
{
system("CLS");
cout << (hours<10?"0":"") << hours <<":" <<
(minutes<10?"0":"") << minutes << ":" << (seconds<10?"0":"") <<
seconds << " " << str << endl;
}
sec_prev=seconds;
}
return 0;
}
Aucun commentaire:
Enregistrer un commentaire