sleep() and usleep() Not Working for Me

I've been trying to figure out how to get my program to pause for a second or two. I've found sleep() and usleep(), but neither are working as they have been explained to do.

These are a couple of locations I got my information from:
http://ubuntuforums.org/showthread.php?t=1425188&highlight=sleep
http://www.dreamincode.net/forums/topic/16391-sleep-command-in-c/

The program should first print out "Hello ", wait 2 seconds then print out "World". But "Hello World" is printed out all at once after a 2 second pause:

Using sleep()
1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
using namespace std;

int main()
{
  cout << "Hello ";
  sleep(2);
  cout << "World";
  cout << endl;
  
  return 0;
}


Using usleep()
1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
using namespace std;

int main()
{
  cout << "Hello ";
  usleep(2000000);
  cout << "World";
  cout << endl;
  
  return 0;
}

Am I not using the functions correctly?
I think sleep() takes milliseconds.

So for a 2 second delay you would want sleep(2000);.
Last edited on
sleep() uses seconds. Sleep() uses milliseconds.
Compyx wrote:
Since the standard library uses buffered I/O, you need to flush the output buffer (holding "Hello") before sleeping. In C I would use
fflush(stdout);

, in C++ I believe
cout.flush();

should do the trick. A newline will also flush the output buffer, but that would break up "Hello World" over two lines.
@Deluge

I tried what you said and it is right .

I used to get confused by the strange behaviour of cin and cout ,nevertheless ,now i get a clear mind about it.So thanks a lot!
Topic archived. No new replies allowed.