Update console

Ok so i have a time function that outputs time, but the problem is it just keeps outputting time in an endless loop. I want there to only be one line and i want the time to update. I do NOT however want to use Win32 or any libraries.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
#include <time.h>
#include <windows.h>

using namespace std;

int main()
{
    while(1)
    {
    time_t current = time(0);
    cout << ctime(&current);
    }
}
1
2
3
4
5
while(1)
{
  time_t current = time(0);
  cout << "\r" << ctime(&current);
}
that still doesnt work.
I do NOT however want to use Win32 or any libraries.


Then you're SOL.

The standard library does not allow you to move the output cursor. So there's no way to overwrite or clear what has already been printed.

If you want to do this, you'll need to use a lib.


EDIT:

Actually you could try backspacing a bunch (is it '\b'? or is that beep?), but that would be implementation dependent at best.
Last edited on
Sorry forgot ctime tacks on a newline when it returns the string...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <time.h>
#include <cstring>
#include <windows.h>

using namespace std;

int main()
{
  while(1)
  {
    time_t current = time(0);
    char *tstr = ctime(&current); 
    tstr[strlen(tstr) - 1] = 0; // ctime returns string with \n, so let's get rid of it...
    cout << "\r" << tstr;
    Sleep(500); // let's not hammer the stdout, mmmmmk?
  }
}
Last edited on
ok well how would i accomplish this in win32? system("cls")? i did that once but the time kept flickering. How do i pause the console window for a short time, i forgot what the keyword is.
Ok cool, it works perfectly, but what is strlen? string length?

"// ctime returns string with \n, so let's get rid of it.."

is that what this is doing " tstr[strlen(tstr) - 1] = 0;" how?
the newline character is the last character of the string, so this is replacing it will a null
Topic archived. No new replies allowed.