gpt4 book ai didi

c++ - 在 for 循环中添加 "time interval"

转载 作者:行者123 更新时间:2023-11-28 06:01:11 25 4
gpt4 key购买 nike

假设我有以下程序(我将只写必要的!):

for (i = 1; i<=100; i++) 
{
cout << " Hello World!\n ";
}

运行将直接产生 100 个 Hello World。我怎样才能使循环在再次执行之前等待一定的持续时间(例如 1 秒)?

最佳答案

自 C++14 起,您可以使用 std::this_thread::sleep_for 以及新的用户定义的时间间隔:

using namespace std::chrono_literals;
for (i = 1; i<=100; i++)
{
cout << " Hello World!\n ";
std::this_thread::sleep_for(1s);
}

Live Example

如果你只有 C++11 支持,那就是

for (i = 1; i<=100; i++) 
{
cout << " Hello World!\n ";
std::this_thread::sleep_for(std::chrono::seconds(1));
}

这确实需要 <thread><chrono>

关于c++ - 在 for 循环中添加 "time interval",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33263407/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com