How to wait in C++?

Is there a simple way to code a one-second "pause"? Just like time.sleep(1) in Python:

import time
print("Ready to Count Down:")
a=60
while ( a>0):
print (a)
time.sleep(1)
a=a-1
print("Happy New Year!")

I tried Sleep(1) and sleep(1) and it didn't work in Xcode.
What does "doesn't work" mean?

There is no such function and you got "unresolved symbol" errors.

Or there is a function, but you saw
- all your strings quickly => you just got the scaling factor on your delay parameter wrong.
- nothing at all for a minute, then all the output you were expecting => use std::flush.

Posting you C++ attempt rather than the Python you cribbed from would have been more useful.
Yes, not figured out the equivalent function.

#include <iostream>
#include <ctime>
using namespace std;
int main()
{
int a = 60;
cout<< "Ready to Count Down:";
while (a>0)
{
cout<<a;
sleep(1); // "Use of undeclared identifier 'sleep'" ERROR.
a--;
}
return 0;

}

Just want to have a similar countdown effect.
The standard C++ solution is verbose but workable (except under Microsoft Windows at the time of writing), for example:
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
#include <chrono>
#include <thread>

int main()
{
  using std::operator""s;
  for (int i = 10; i > 0; --i)
  {
    std::cout << i << ' ' << std::flush; 
    std::this_thread::sleep_for(1s); 
  } 
}


If you're concerned with Windows compatibility, see this post:
http://www.cplusplus.com/forum/beginner/279136/#msg1205750

The alternative there is to call Sleep from synchapi.h
https://docs.microsoft.com/en-us/windows/win32/api/synchapi/nf-synchapi-sleep
Last edited on
Thanks. Exactly what I want it to be!
This how I do it in visual studio :)
1
2
3
4
5
6
7
8
9
#include<iostream>
#include <windows.h>
using namespace std;
int main()
{
cout<<"There will be a pause after this phrase\n";
Sleep(3000)
cout<<"Told you...";
}

The number you input in parenthesis is millisecond (1000 ms = 1 sec)
S in Sleep has to be capital
Last edited on
Sleep is for windows. its not portable to other os (i.e. mac, android)

so, use this this_thread::sleep_for(1s); //needs #include <thread> & #include <chrono>
I think I read somewhere the there are Windows compatibility problems with std::this_thread::sleep_for and an alternative is to call Sleep from synchapi.h.

https://www.cplusplus.com/forum/beginner/280066/#msg1210663

Try this, it's a slight adaptation from https://stackoverflow.com/questions/158585/how-do-you-add-a-timed-delay-to-a-c-program

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

int main() {
    using namespace std::this_thread;     // sleep_for, sleep_until
    using namespace std::chrono_literals; // ns, us, ms, s, h, etc.
    using std::chrono::system_clock;

    std::cout << "Start\n";
    
    sleep_for(10ns);
    sleep_until(system_clock::now() + 10s);
    std::cout << "Done\n";
}
Topic archived. No new replies allowed.