C++ sleep for seconds
Code to Sleep for Seconds in C++
#include <iostream>
#include <chrono>
#include <thread>
int main() {
std::cout << "Sleeping for 3 seconds..." << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(3));
std::cout << "Awake!" << std::endl;
return 0;
}
Explanation
Include Required Headers: Include the necessary headers for input/output, time, and threading using
#include
directive.Main Function: Define the main function as the entry point of the program.
Print Message: Output a message to indicate that the program is about to sleep for a specified duration.
Sleep for 3 Seconds: Use
std::this_thread::sleep_for
to make the program sleep for 3 seconds, specified usingstd::chrono::seconds(3)
.Print Wake-Up Message: Output a message to indicate that the program has woken up.
Return 0: Return 0 to indicate successful execution of the program.
This code demonstrates how to make a C++ program sleep for a specified number of seconds using the <chrono>
and <thread>
libraries.