Search code examples
c++sleep

Pause For-Loop for 1 second in C++


I have an loop, but it goes to fast. I need something simple and easy to use, to pause it for 1 sec in each loop.

for(int i=0;i<=500;i++){
   cout << "Hello number : " << i;
   //i need here something like a pause for 1 sec
}


Solution

  • std::this_thread::sleep_for is exactly what you're looking for.

    for(int i=0;i<=500;i++){
        cout << "Hello number : " << i;
        std::this_thread::sleep_for(1s);
    }
    

    To use it like that, you need to include <chrono> and <thread> and then add using namespace std::chrono_literals;. It also requires c++11 enabled.