【C语言】关于printf的缓冲区问题

【C语言】关于printf的缓冲区问题

前言

使用printf时,发现要打印的东西并没有打印出来,而是要等到下次printf(“\n”)或者程序退出时才会一起打印出来。

代码示例:

#include

#include

#include

int main()

{

printf("hello world");

sleep(5);

printf("\n");

printf("hello world again");

sleep(5);

exit(0);

}

运行结果:hello world并不是立刻打印出来,而是等第一个5s阻塞结束才打印出来;同样的,hello world again也是等到程序退出时才打印出来。

一、原因

printf是有缓冲区的,并不是直接将内容输出到屏幕上,它会先将需要输出的内容放入到缓冲区,直到缓冲区满或者遇到"\n"或者程序结束才将内容输出的屏幕上。

二、解决方法

1.关闭缓冲区:setbuf(stdout,NULL)

代码如下(示例):

#include

int main(void)

{

int i=0;

setbuf(stdout,NULL); // 关闭缓冲区

for(i=0; i<10; i++)

{

printf("hello world");

sleep(1);

}

return 0;

}

运行结果:hello world

2.刷新缓冲区:fflush(stdout)

代码如下(示例):

#include

#include

#include

int main()

{

printf("hello world");

fflush(stdout); //刷新缓冲区

sleep(1);

exit(0);

}

运行结果:hello world

🎀 相关推荐

聂怎么读
🎯 beat365娱乐网址

聂怎么读

📅 07-04 👀 8366
乌龟为什么长寿?
🎯 beat365娱乐网址

乌龟为什么长寿?

📅 06-29 👀 9869
顺丰快递一台笔记本电脑要多少 用顺丰邮寄个电脑大概要多少钱?