I suggest this:

#include <iostream> #include <ctime> using namespace std; int main() { double tim; tim = time(0); while(time(0) - tim != 2) { } cout << "hello world"!; while (time(0) - tim != 2) { } } 

Are there any other options?

  • 2
    It is not good to occupy the CPU with stupid cycles. Look at the answer @Kremchik. You can also use select (). - avp 2:19 pm
  • By the way, slow down or stop? ... - Ivlev Denis
  • one
    And making c using while pause, you lose control of the program. - Ivlev Denis
  • one
    Idea (as old as the world): put the function into a separate thread, which we should manage. It remains only to make the synchronization of threads. - Ivlev Denis
  • Suspend. Sorry, not so expressed. - sudo97

5 answers 5

 #include <unistd.h> ... ... sleep(2);//2 сСкунды usleep(1000000);//1 сСкунда (1.000.000 микросСкунд) 

It is necessary to take into account that by checking these functions printf is necessary either to finish the print on "\n" , or to install flush immediately after the print: fflush(stdout); , eg:

 printf("1"); fflush(stdout); sleep(1); printf(" - 2"); 

The same goes for cout. Analog to fflush (stdout) - cout.flush ();

PS In Windows, this is not the case, but there is a replacement:

 #include <windows.h> Sleep(1000);//1 сСкунда - 1.000 миллисСкунд 
  • sleep also kills program management ... - Ivlev Denis
  • Well, so use streams. - ArtFeel
  • If I understand correctly: there is a function sleep (); which takes time in seconds and pauses the program for this time. So? And it is in the unistd.h library. Is that right? - sudo97
  • Ilya, yes, that's it. With the proviso that this is in Linux. On Windows, there is a Sleep function (milliseconds) in the windows.h library. For greater accuracy, Linux uses the usleep (microsek) function, for example, 500 thousand microseconds will be for half a second. - ivkremer pm
  • one
    Conclusion: the use of threads is the most profitable way to control the execution of the program. - Ivlev Denis

A canonical C ++ way is to use std::this_thread::sleep_for

 #include <chrono> #include <thread> int main() { std::this_thread::sleep_for(std::chrono::seconds(2)); } 

Starting with C ++ 14 you can write

 using namespace std::literals; std::this_thread::sleep_for(2s); 
  • one
    Nevertheless, it is a method to suspend only a single-threaded program. - VladD
  1. sleep () and delay () - from the standard sy's library (I do not remember which one),
  2. Sleep () - WinAPI from windows.h
  3. Use for delay cycles for, while. Also heard still there is a function wait ();

    sleep () and delay () is a nice little article.

       #include <iostream> int main(){ using namespace std; for (float ex = 0; ex <=4; ex=ex+0.10) { system("cls"); cout<<"Exit through 4 second"<<endl; cout<<" "; } exit(0); return 0; } 

      As an option)

      • add an explanation of what exactly happens in the code - Grundy