hi , i am using simple console application and i am asking about the way to make the program depend on time insead of dependng on pressing keys for example, i want siplay the word "Hello.." and after 5 seconds it changes to "World" , to elaborate .. i want system("pause") but depending on time not on keys.
thnx :idea:

Something like this?

#include <stdio.h>
#include <time.h>

int main(void)
{
   time_t now, then = time(&now) + 5;
   if ( now != (time_t)(-1) )
   {
	  const char *text[] = {"Hello","World"};
	  size_t i = 0;
	  for ( ;; )
	  {
		 printf("\r%s", text[i]);
		 fflush(stdout);
		 if ( ++i >= sizeof text / sizeof *text )
		 {
			i = 0;
		 }
		 while ( then > time(&now) );
		 then = now + 5;
	  }
   }
   return 0;
}

Hello,

Unfortunately, that code above is unfriendly to other processes on the computer, because of the infinite loop that is run. Granted, in this close example, you are looking at 5 seconds, and that won't cause something to croke.

But, if I had to do a delay in the minutes range, that would peg the CPU, and cause a system admin to come and shut you down. That might not matter today, but back in the day when CPU seconds = money on the mainframe, a loop like that could run you out of money.

There has to be a better way without doing the raw iteration!

(I had a program that needed the delay, and I ended up using a part C++ program and part of a BASH shell script so that I could do the wait() command that did not use CPU power during the delay)

Christian

You could use GetTickCount().

double next_time  = GetTickCount();

while (true)
{
       if(GetTickCount() >=next_time + 100)
       {
             cout<<"Bong\n";
             next_time  = GetTickCount();
       }
}
This article has been dead for over six months. Start a new discussion instead.