为什么这个程序要等10秒而不是倒数?

How come this program waits 10 seconds instead of counting down?

本文关键字:倒数 10秒 程序 为什么      更新时间:2023-10-16

我正在尝试一些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";
}