★
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