在 C++ 中暂停 For 循环 1 秒
Pause For-Loop for 1 second in C++
我有一个循环,但速度很快。我需要一些简单易用的东西,在每个循环中暂停 1 秒。
for(int i=0;i<=500;i++){
cout << "Hello number : " << i;
//i need here something like a pause for 1 sec
}
std::this_thread::sleep_for
正是您要找的。
for(int i=0;i<=500;i++){
cout << "Hello number : " << i;
std::this_thread::sleep_for(1s);
}
要这样使用它,您需要包含 <chrono>
和 <thread>
,然后添加 using namespace std::chrono_literals;
。它还需要启用 c++11
。
如果您使用 windows 平台,这可能会有所帮助:
#include <windows.h> //winapi header
Sleep(1000);//function to make app to pause for a second and continue after that
Sleep(n) 是一个准备好的方法。要使用此方法,请不要忘记同时添加“windows.h”头文件,并记住 'n' 是您可能希望延迟代码执行的毫秒数。重复“Hello world!”的简单代码可以看到:
#include <iostream>
#include <windows.h>
using namespace std;
int main()
{
for(int i=0;i<10;i++)
{
cout << "Hello world!" << endl;
Sleep(1000);
}
return 0;
}
我有一个循环,但速度很快。我需要一些简单易用的东西,在每个循环中暂停 1 秒。
for(int i=0;i<=500;i++){
cout << "Hello number : " << i;
//i need here something like a pause for 1 sec
}
std::this_thread::sleep_for
正是您要找的。
for(int i=0;i<=500;i++){
cout << "Hello number : " << i;
std::this_thread::sleep_for(1s);
}
要这样使用它,您需要包含 <chrono>
和 <thread>
,然后添加 using namespace std::chrono_literals;
。它还需要启用 c++11
。
如果您使用 windows 平台,这可能会有所帮助:
#include <windows.h> //winapi header
Sleep(1000);//function to make app to pause for a second and continue after that
Sleep(n) 是一个准备好的方法。要使用此方法,请不要忘记同时添加“windows.h”头文件,并记住 'n' 是您可能希望延迟代码执行的毫秒数。重复“Hello world!”的简单代码可以看到:
#include <iostream>
#include <windows.h>
using namespace std;
int main()
{
for(int i=0;i<10;i++)
{
cout << "Hello world!" << endl;
Sleep(1000);
}
return 0;
}