关于 C/C++ 的输入输出缓冲



printf 无缓冲,cout 有缓冲;
缓冲刷新的时刻有:
1. 缓冲区满;
2. 输出 endl;
3. 显式调用 flush 函数;
4. 程序结束时。



C 中缓冲设置相关的函数:setbuf()



cout.setf(ios::stdio);
上述语句让 iostream 和 stdio 共用一个缓冲。



程序1:

#include "iostream.h"
#include "stdio.h"

int main()
{
    cout << "ok1";
    printf("%s", "ok");
    cout << "ok2";

    return 0;
}


程序1在 vc 6.0 里的输出结果为:
okok1ok2
其原因是:cout << "ok1"; 的时候没有刷新缓冲区,而 printf 输出后就刷新了。当 cout << "ok2"; 的时候,缓冲仍然没有被刷新。直到退出程序的时候,iostream 才刷新它的缓冲。所以 cout 的输出在 printf 后面。如果要顺序输出的话,在 cout 语句最后加上 << endl (cout << "ok1" << endl;),endl 会刷新缓冲的。

在 gcc 和 vs.net 中的输出正常,如下:
ok1okok2

程序2:

#include "iostream.h"
#include "stdio.h"

int main()
{
    cout << "ok1"; 
    printf("%s", "ok"); 
    cout << "ok2";
    for (int i = 1; i = 1; )
    {
        ;
    }

    return 0;
}


程序2在 vc 6.0 里的输出结果为:
ok
其原因是:程序最后有个无限循环,所以cout没有机会被刷新(一般程序退出的时候 cout 会被刷新缓冲)。

在 gcc 和 vs.net 中的输出正常,如下:
ok1okok2



在多线程中用 printf 的话,其中的内容往往能在一个时间片内输出;而如果用 cout 的话,就不能够保证是否能在一个时间片内输出,即使加了 flush 或 endl 也一样。


参考:
1. http://topic.csdn.net/t/20020707/12/855968.html
2. http://bbs.sjtu.edu.cn/bbsanc,path,%2Fgroups%2FGROUP_1%2FACMICPC%2Ftemporary%2FD4D425840%2FM.1054035254.A.html
3. http://community.csdn.net/Expert/TopicView3.asp?id=5030264
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值