C++中有等待函数吗?
Is there a wait function in C++?
我一直在编写一个程序,它使用了 sleep() 函数。我希望它是 macOS、Linux 和 Windows 的跨平台,但是拥有三个分支使用起来既乏味又糟糕。我该怎么做才能使其跨平台?以及使程序等待几秒钟的功能是什么?当我测试它时,它甚至不起作用...
Linux 代码好像不能用...
#include <iostream>
#include <unistd.h>
using namespace std;
int loading() {
sleep(0.25);
cout << "Loading... ";
sleep(0.25);
cout << "hi";
sleep(0.25);
cout << "e";
sleep(0.25);
return 0;
}
int main() {
loading();
return 0;
}
Windows...
#include <iostream>
#include <windows.h>
using namespace std;
int loading() {
Sleep(250);
cout << "Loading... ";
Sleep(250);
cout << "hi";
Sleep(250);
cout << "e";
Sleep(250);
return 0;
}
int main() {
loading();
return 0;
}
是语法错误,还是我使用不正确?
从 C++11 开始,您可以使用 std::this_thread::sleep_for
using namespace std::chrono_literals;
std::this_thread::sleep_for(250ms);
我一直在编写一个程序,它使用了 sleep() 函数。我希望它是 macOS、Linux 和 Windows 的跨平台,但是拥有三个分支使用起来既乏味又糟糕。我该怎么做才能使其跨平台?以及使程序等待几秒钟的功能是什么?当我测试它时,它甚至不起作用...
Linux 代码好像不能用...
#include <iostream>
#include <unistd.h>
using namespace std;
int loading() {
sleep(0.25);
cout << "Loading... ";
sleep(0.25);
cout << "hi";
sleep(0.25);
cout << "e";
sleep(0.25);
return 0;
}
int main() {
loading();
return 0;
}
Windows...
#include <iostream>
#include <windows.h>
using namespace std;
int loading() {
Sleep(250);
cout << "Loading... ";
Sleep(250);
cout << "hi";
Sleep(250);
cout << "e";
Sleep(250);
return 0;
}
int main() {
loading();
return 0;
}
是语法错误,还是我使用不正确?
从 C++11 开始,您可以使用 std::this_thread::sleep_for
using namespace std::chrono_literals;
std::this_thread::sleep_for(250ms);