alexo1001
alexo1001

Reputation: 307

sleep statement not working properly in C++

I have been using the sleep statement like this: sleep(2); for a while but now it suddenly doesn't work properly anymore. Whenever I run this code (example):

#include <iostream>
using namespace std;

int main()  {
    cout << "Hi";
    sleep(2);
    cout << "Hello";
}

instead of saying "Hi" first then waiting two seconds and then saying "Hello", it first waits two seconds and then it displays both "Hi" and "Hello". I have other pieces of code that I wrote before and they do not have the problem, but as soon as I create a new target && file and try to write some code with the sleep statement in it, it does the same thing again, :(. Please help me fix this guys, thanks!

Upvotes: 2

Views: 1025

Answers (2)

OhadM
OhadM

Reputation: 4803

According to std reference, you should use:

std::this_thread::sleep_for(2s);

Of course, if you are using multi-thread environment this is best practise.

Upvotes: 1

MikeCAT
MikeCAT

Reputation: 75062

Try flushing the buffer.

#include <iostream>
using namespace std;

int main()  {
    cout << "Hi";
    cout << flush; // add this line
    sleep(2);
    cout << "Hello";
}

Upvotes: 4

Related Questions