首页 > 解决方案 > printf() 函数在 time() 函数之后执行?C/C++

问题描述

我写了以下程序:

#include <cstdio>
#include <ctime>
int main()

{
time_t t;
int d;
printf("\nHello 1");    
    time(&t);           
    d=t;
    while (t-d<3) /*wait 3 seconds*/
    {
        time(&t);
    }
printf("\nHello 2");
    time(&t);
    d=t;
    while (t-d<3)  /*wait 3 seconds*/
    {
        time(&t);
    }
printf("\nHello 3");
return 0;
}

构建程序后,我运行它。程序等待 3 秒以显示“Hello 1”行。

为什么先写后执行?

标签: c++

解决方案


在某些操作系统上,输出缓冲区stdout通常需要“刷新”才能使您在那里打印的内容出现在屏幕上。\n充当“冲洗”并解释了行为。

您可以通过fflush(stdout);在每个printf. 这会强制进行屏幕更新。或者将 移动\n到每行的末尾而不是开头。


推荐阅读