我一直在开发一个程序,它使用了 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;
}
是语法错误,还是我使用不正确?
std::this_thread::sleep_for
using namespace std::chrono_literals;
std::this_thread::sleep_for(250ms);
您还可以使用更简单的方法,仍然使用 Sleep_for:
#include <iostream>
#include <chrono>
#include <thread>
int main(){
std::this_thread::sleep_for(std::chrono::seconds(1));
}
通常总是对我有用,你也可以从秒更改为毫秒,ecc...