BludBerg
BludBerg

Reputation: 55

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
}

Upvotes: 2

Views: 6774

Answers (3)

BludBerg
BludBerg

Reputation: 55

If you use windows platform this may help:

#include <windows.h> //winapi header  

Sleep(1000);//function to make app to pause for a second and continue after that 

Upvotes: 1

mohamad bari
mohamad bari

Reputation: 45

Sleep(n) is a prepared method. To use this method do not forget to add "windows.h" header file as well and remember 'n' is the millisecond you may wish to delay the code execution. A simple code which repeats "Hello world!" can be seen:

#include <iostream>
#include <windows.h>
using namespace std;

int main()
{

    for(int i=0;i<10;i++)
    {
     cout << "Hello world!" << endl;
     Sleep(1000);
    }

    return 0;
}

Upvotes: 1

Denis Sheremet
Denis Sheremet

Reputation: 2583

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.

Upvotes: 6

Related Questions