How to Code a C++ Wait Function

When coding in C++, it can be helpful to halt the program's execution temporarily for purposes such as animation or giving the user time to read the screen. For example, you could display some text to the user, have the program wait five seconds and then continue executing code. Various "sleep" functions are available, depending on the operating system you are running, since it requires accessing the system clock.

Instructions

    • 1

      Open the C++ file in an editor such as Microsoft Visual Studio Express.

    • 2

      Include the "Windows.h" header, in Windows, so you can access the "sleep" function by adding the following code at the top of your file:

      #include <windows.h>

      Alternatively, if using Unix, include the "unistd.h" header instead with the code:

      #include <unistd.h>

    • 3

      Call the "sleep" function in Windows to pause execution of the program for a specified amount of time by adding the following code in your function:

      sleep(1000); // 1 second

      The numeric argument is in milliseconds, so 1,000 ms = 1 second.

      Alternatively, in Unix, call the "sleep" or "usleep" functions to pause execution, with the code:

      sleep(1); // 1 second

      usleep(500000); // 0.5 second

      The Unix "sleep" function's argument is measured in seconds. The "usleep" function's argument is measured in microseconds, which is one millionth of a second. The argument for the "usleep" function must be less than one million.

    • 4

      Save the C++ file, compile and run the program to use the sleep function.

Related Searches:

References

Comments

Related Ads

Featured