Oct 21, 2012 at 6:52am UTC
Hey so im trying to do some practice in c++, and this seemed like a good challenge. So far all i can do is get seconds to go up to 60, then all hope is lost:P heres what i have so far, please give me some direction on how to get the reest going.. my thinking is probably a funtion for each time (ie getHours, getMins, getSeconds, etc.). Any help will be awesome!
BTW i am using the <iostream> library..
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
#include <iostream>
#include <iostream>
using namespace std;
int main()
{
int hour = 1;
int min = 00;
int sec = 00;
while (sec < 60) {
cout << hour << ":" << min << ":" << sec << endl;
sec++;
}
while (min < 60){
cout << hour << ":" << min << ":" << sec << endl;
min++;
}
system("pause" );
}
EDIT: I cant seem to show you guys the output of the program..i use cmd to run it, and i cant copy the content. any help?
Last edited on Oct 21, 2012 at 6:53am UTC
Oct 21, 2012 at 7:31am UTC
I would use nested for loops, rather than while.
Challenge: Should be able to do it in 5 lines (not counting includes, namespace etc)
BTW i am using the <iostream> library..
I can see that - you have it in there twice!!
Consider using
std::cout
instead of
using namespace std;
Something similar for other std things like cin, endl etc.
Hope all goes well.
Edit :
int sec = 00;
Doesn't do what you think it does.
Last edited on Oct 21, 2012 at 7:32am UTC
Oct 21, 2012 at 9:03am UTC
So do you want to display a timespan (time difference) or just current time ?
Oct 21, 2012 at 2:53pm UTC
Hmmm, a way to go to meet the 5 line challenge.
One immediate short cut is to output in 12:23:16 format.
Another observation is that 12 hours of out put is 12*60*60 = 43,200 lines
Oct 21, 2012 at 4:00pm UTC
I took the 5-line challenge :)
1 2 3 4
for (int hh = 1; hh <= 12; ++hh)
for (int mm = 0; mm < 60; ++mm)
for (int ss = 0; ss < 60; ++ss)
printf("%2d:%02d:%02d\n" , hh, mm, ss);
4 line
My first thought of this problem is using strftime (
http://www.cplusplus.com/reference/clibrary/ctime/strftime/)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
#include <iostream>
#include <time.h>
#include <windows.h>
int main ()
{
time_t rawtime;
struct tm *timeinfo;
char buffer[10];
while (true )
{
time(&rawtime);
timeinfo = localtime(&rawtime);
strftime(buffer,10,"%I:%M:%S" ,timeinfo);
std::cout << buffer << std::endl;
Sleep(1000);
}
return 0;
}
Last edited on Oct 21, 2012 at 4:03pm UTC
Oct 21, 2012 at 10:16pm UTC
I like the first one, that's what I was thinking.
The second one will take 12hours to complete!! go on forever!!! It shows how careful you need to be with infinite loops.
I hope the OP & others have learnt a little bit today.
Last edited on Oct 21, 2012 at 10:18pm UTC