954,496 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

how can i make the program depend on time

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:

dooda man
Newbie Poster
15 posts since May 2004
Reputation Points: 10
Solved Threads: 0
 

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;
}
Dave Sinkula
long time no c
Team Colleague
5,058 posts since Apr 2004
Reputation Points: 2,780
Solved Threads: 314
 

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

kc0arf
Posting Virtuoso
Team Colleague
1,937 posts since Mar 2004
Reputation Points: 121
Solved Threads: 57
 

You could use GetTickCount().

double next_time  = GetTickCount();

while (true)
{
       if(GetTickCount() >=next_time + 100)
       {
             cout<<"Bong\n";
             next_time  = GetTickCount();
       }
}
FireNet
Posting Whiz in Training
258 posts since May 2004
Reputation Points: 108
Solved Threads: 7
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You