I have some code and i want to be able to update the time it displays so it looks like the clock is ticking without having to quit and run the program again. Also can you explain the code, i didnt write it, i found it on a website under examples. I dont quite fully understand it, i understand what the output does but i dont understand what its doing to get it. Also can you please explain it in lamens terms please. Thanks.
1 2 3 4 5 6 7 8 9 10 11
#include <iostream>
#include <time.h>
usingnamespace std;
int main()
{
time_t current = time(0);
cout << ctime(¤t)<< endl;
}
time_t is a type used to hold time values. Usually represents the number of seconds since 1970.
time(0) returns the current time as a time_t object.
ctime() converts the parameter to a human readable string representing the time stored.
If you just output current you'd get some huge number.
You could just put the whole thing in a loop:
What i want is the time to be on one line, and it updates the time to show it ticking, i want basically what its doing now except i want it to look like its only one line.
I tried that though but it just kept making a bunch of lines with updated text, i swore there was a way to do it, without Winapi, cause i know how to do it using system("cls"); but i dont want to use it :(
// At the top of your program.. And don't forget to #include < ctime>
HANDLE console = GetStdHandle(STD_OUTPUT_HANDLE);
COORD CursorPosition;
void gotoXY(int x, int y)
{
CursorPosition.X = x;
CursorPosition.Y = y;
SetConsoleCursorPosition(console,CursorPosition);
}
1 2 3 4 5 6
while (1)
{
time_t current = time(0); // Inside of int main()
gotoXY(35,21);
cout << "The time is : " << ctime(¤t) << flush;
}
Regrettably, I did not check to make sure that ctime() works the way it is presented. It produces a string with a '\n' newline at the end. You need to strip that before printing.
1 2 3 4 5 6
while (1)
{
string s = ctime(¤t);
s.resize( s.length() - 1 );
cout << "\r" << s << flush;
}