how to delay text in c++ console app
#include <iostream>
#include <chrono>
#include <thread>
int main() {
std::cout << "This is some text." << std::endl;
// Delay for 2 seconds
std::chrono::seconds duration(2);
std::this_thread::sleep_for(duration);
std::cout << "Delayed text after 2 seconds." << std::endl;
return 0;
}
Explanation:
#include <iostream>
: Includes the input/output stream header file, allowing for input and output operations.#include <chrono>
: Includes the header file for handling time durations.#include <thread>
: Includes the header file for multi-threading support.int main() { ... }
: The main function where the program execution starts.std::cout << "This is some text." << std::endl;
: Prints the text "This is some text." to the console.std::chrono::seconds duration(2);
: Creates a duration of 2 seconds using thestd::chrono
library.std::this_thread::sleep_for(duration);
: Pauses the execution of the program for the specified duration (2 seconds in this case), causing a delay.std::cout << "Delayed text after 2 seconds." << std::endl;
: Prints the text "Delayed text after 2 seconds." to the console after the delay.return 0;
: Indicates successful program execution and exits the main function.