为什么这个程序要等10秒而不是倒数?
How come this program waits 10 seconds instead of counting down?
我正在尝试一些c++11代码,我试图编写一个程序,从10开始倒数,在输出之间睡觉。以下是目前为止的内容:
#include <iostream>
using namespace std;
#include <chrono>
#include <thread>
void Sleep(int x)
{
std::this_thread::sleep_for(std::chrono::duration<int>(x));
}
int main()
{
for (int x=10; x>0; x--) {
cout << x << "...";
Sleep(1);
}
cout << " FIRE!!n";
}
问题是,这段代码等待10秒,然后打印所有输出,而不是从10开始倒数。这是怎么回事?我该怎么补救呢?
(顺便说一下,我在一台运行Linux Mint 17和MacOSX 10.9的计算机上尝试了这个,两次我都得到了相同的结果)
可能是因为您没有刷新输出。试试这个
cout << x << "..." << flush;
流输出可以被缓冲,这意味着结果并不总是立即出现。刷新至少增加了您立即看到一些输出的机会。
您需要在每次循环中刷新输出,否则运行时系统将等待缓冲区填满或(有时)发送行尾。
同样,当使用std::chrono::duration<>
时,如果可能的话,最好使用显式定义的类型之一,以提高可读性。在这种情况下,您以秒为单位测量时间,所以我在您的示例中使用std::chrono::seconds
:
#include <iostream>
using namespace std;
#include <chrono>
#include <thread>
void Sleep(int x)
{
// better to use explicit types for duration
// for readability
std::this_thread::sleep_for(std::chrono::seconds(x));
}
int main()
{
for(int x = 10; x > 0; x--) {
cout << x << "..." << std::flush; // need to flush here
Sleep(1);
}
cout << " FIRE!!n";
}
相关文章:
- CMake项目Boost库错误:Boost/config/compiler/gcc.hpp:165:10:致命错误:cs
- OpenInventor从9.8升级到10.4.2后,GLSL纹理返回零
- 为什么我不能在 FOR LOOP 中使用 i/10,C++?
- 标准是否使用多余的大括号(例如 T{{{10}}})定义列表初始化?
- Windows 10-使用gtkmm-3.0库和g++[包括再现]的分段故障
- clang整洁10忽略了我的NOLINT命令
- 如何解决错误:SCIP C++中的 SCIP 阶段无效 <10>
- Grpc 客户端C++通道析构函数需要 10 秒
- 无限循环在5到10秒后停止工作
- 如何在将秒转换为分钟且余数小于 10 秒时包含前导零
- 带有 Rebel t6i 的 OS X 10.12.1 上的 EDSDK 3.4.0:拍摄照片后最多 30 秒内不会收到
- 如果STD :: COUT发表评论,则计时器需要更长的时间才能达到10.f秒
- 我的SFML项目在约10秒后崩溃
- 唯一的 10 位序列 ID - 200 个 ID/秒
- 每 10 秒循环一次
- 如何通过cublasCreate()减少巨大的时间成本(10秒)
- 如何使用' cin '在c++中暂停程序10秒
- 为什么这个程序要等10秒而不是倒数?
- c++如何每10秒检查一次时间
- 什么可以使纳米睡眠漂移在 mac OS X 10.9 上正好 10.9 秒