How to make DELAY between cout Statements

Hey guys, I would like to learn to put a delay between output and input statements.

How can I do this?

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

using namespace std;

int main()
{
	cout << "This is one line of text" << endl;

// Wait about 3-5 seconds
	
	cout << "I want this line of text to display about 5 seconds after the first line" << endl;
	
	return 0;
}
Last edited on
You could use a timer with something from ctime http://www.cplusplus.com/reference/ctime/ or use sleep() or Sleep() depending on platform.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#ifdef _WIN32

  #include <windows.h>

  inline void delay( unsigned long ms )
    {
    Sleep( ms );
    }

#else  /* POSIX */

  #include <unistd.h>

  inline void delay( unsigned long ms )
    {
    usleep( ms * 1000 );
    }

#endif 

All sane Windows compilers must #define _WIN32, but if yours doesn't make sure it gets defined at some point before this code.

Works on Windows and *nix/OS X.

Hope this helps.
Duoas, I thought someone said that usleep() is deprecated and nanosleep() is better, but I could be wrong..
Would you say that this implementation is better than http://en.cppreference.com/w/cpp/thread/sleep_for ? I was going to use sleep for an updating program and wasn't sure which to choose.
Last edited on
Thanks guys, the sleep() function worked fine (on windows)
I've learned something. Thanks Ganado!

Yes, POSIX has dropped usleep() for nanosleep(), but usleep() isn't going away any time soon. (Untold numbers of programs rely on it.) And particularly as nanosleep() is quite a bit more clunky to use.

In a POSIX environment, you could also select() on a NULL file descriptor set for a certain amount of time.

The this_thread.sleep_for( N ) is preferred in newer C++11 compilers.
Topic archived. No new replies allowed.