我尝试在Linux中进行一个简单的测验:
#include <stdio.h>
#include <unistd.h>
void main()
{
printf("Simple arithmetic\n");
printf("5 * 7 + 4 / 2 = ?\n");
sleep(3); //wait for 3 seconds
printf("And the answer is");
for(int i = 5; i > 0; i--){ //wait for another 5 seconds printing a '.' each second
sleep(1);
printf(" .");
}
printf("\n%d!\n", 5*7+4/2); //reveal the answer
}
问题是,这会输出frist两个printf&#39;然后等待8秒左右,然后打印出其他所有内容:
>> Simple arithmetic
>> 5 * 7 + 4 / 2 = ?
>> // waits for 8 seconds instead of 3
>> And the answer is.....
>> 37! // prints everything out with no delay in-between
为什么会发生这种情况,我该怎么做才能解决这个问题?谢谢你的帮助!
答案 0 :(得分:2)
需要刷新。
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
void main()
{
printf("Simple arithmetic\n");
printf("5 * 7 + 4 / 2 = ?\n");
sleep(3); //wait for 3 seconds
printf("And the answer is");
for(int i = 5; i > 0; i--){ //wait for another 5 seconds printing a '.' each second
sleep(1);
printf(" .");
fflush(stdout); // this line will do magic
}
printf("\n%d!\n", 5*7+4/2); //reveal the answer
}