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);


以上是C++中是否有等待函数?的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>