Sunday, July 12, 2009

How can i make a c++ program pause for a set number of seconds, say 5?

Im trying to find code that will let me pause a program for a set amount of time. ideally i would like to use the system time or a c++ function specifically for delaying a program if there is one.


What header are these functions under? And im talking Windows specific.

How can i make a c++ program pause for a set number of seconds, say 5?
#include %26lt;time.h%26gt;





void sleep(unsigned int mseconds)


{


clock_t goal = mseconds + clock();


while (goal %26gt; clock());


}
Reply:if you are using TC++ IDE you can use delay() to pause program for specified miliseconds. eg


delay(400) pauses execution for 400 miliseconds. You can see its best example (Titled "Timer") on blog http://codesbyshariq.blogspot.com
Reply:Windows is message-driven, so you aren't supposed to lock up the CPU for any length of time. The "correct" way to do this is in Windows is with a one-shot timer, i.e. call SetTimer() with a time period of 5000 ms and then catch the WM_TIMER message when it arrives and respond accordingly. This will ensure that your message loop continues running and your program doesn't lock up for those 5 seconds.





If you're absolutely determined to lock your thread then call the Sleep() function so that you at least free up the CPU for any other processes that are running.
Reply:#include %26lt;time.h%26gt;





int pause(int secs)


{


time_t t = time(NULL) + secs;


while (time(NULL) %26lt; t);


}


No comments:

Post a Comment