How to wait time in c++?

by taya_block , in category: C/C++ , 2 years ago

How to wait time in c++?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by dmitrypro77 , 2 years ago

@taya_block use sleep() function to wait time in C++, code:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
#include <iostream>
#include <unistd.h>

int main(int argc, char *argv[]) {
    std::cout << "Hello, lets wait 10 seconds!" << std::flush;
    // Wait 10 seconds
    sleep(10);
    std::cout << "Done! Thanks!";
    return 0;
}


Member

by adrianna , 9 months ago

@taya_block 

In C++, you can wait for a specific amount of time using the <thread> library. Here's an example of how to wait for 2 seconds:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
#include 
#include 
#include 

int main() {
    std::cout << "Before waiting" << std::endl;
    
    // Wait for 2 seconds
    std::this_thread::sleep_for(std::chrono::seconds(2));
    
    std::cout << "After waiting" << std::endl;
    
    return 0;
}


In the above example, std::this_thread::sleep_for() is used to pause the execution of the program for 2 seconds. The std::chrono::seconds(2) argument specifies the duration of the delay. You can use other durations, such as milliseconds or microseconds, by changing the argument passed to sleep_for().