现在的cout不需要buffer了?该如何解决
现在的cout不需要buffer了??
网上总说cout是被缓冲的,调用cout.flush()才能将要输出的内容显示在屏幕上,可小弟用微软网站提供的测试cout缓冲的程序,却发现不调用cout.flush()也能将内容显示出来。
编译器:Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 13.10.3077 for 80x86
代码 :
#include <iostream>
#include <time.h>
using namespace std;
int main( )
{
time_t tm = time( NULL ) + 5;
cout < < "Please wait... ";
while ( time( NULL ) < tm )
;
cout < < "\nAll done " < < endl;
}
测试预期:程序启动5秒后 "Please wait... "和 "\nAll done "一起显示。
测试结果:程序启动立即显示 "Please wait... ", "\nAll done "5秒钟后才显示。
微软的网站上也说cout是被缓冲的,可为什么 "Please wait... "一开始就被显示出来了呢?
请高手不吝赐教
------解决方案--------------------
cout < < "Please wait... ";
和cout < < "\nAll done " < < endl;
是在同一行输出的内容,因此会在5秒后一起输出。
类似的把cout改成printf也是一样的结果。
解决的办法是:
cout < < "Please wait... " < <endl;
或者printf( "Please wait...\n ");
如果一定不要换行则在cout < < "Please wait... ";后加一句:cout.flush();
------解决方案--------------------
int main( )
{
char* pbuffer = new char[1024];
setbuf(stdout, pbuffer);
time_t tm = time( NULL ) + 5;
cout < < "Please wait... ";
while ( time( NULL ) < tm )
;
cout < < "\nAll done " < < endl;
delete pbuffer;
}
------解决方案--------------------
char* pbuffer = new char[1024];
setbuf(stdout, pbuffer);
印象中,block buffer 的缓冲区大小是有特定常量表示的,不是随便一个 1024 的缓冲都可以。
网上总说cout是被缓冲的,调用cout.flush()才能将要输出的内容显示在屏幕上,可小弟用微软网站提供的测试cout缓冲的程序,却发现不调用cout.flush()也能将内容显示出来。
编译器:Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 13.10.3077 for 80x86
代码 :
#include <iostream>
#include <time.h>
using namespace std;
int main( )
{
time_t tm = time( NULL ) + 5;
cout < < "Please wait... ";
while ( time( NULL ) < tm )
;
cout < < "\nAll done " < < endl;
}
测试预期:程序启动5秒后 "Please wait... "和 "\nAll done "一起显示。
测试结果:程序启动立即显示 "Please wait... ", "\nAll done "5秒钟后才显示。
微软的网站上也说cout是被缓冲的,可为什么 "Please wait... "一开始就被显示出来了呢?
请高手不吝赐教
------解决方案--------------------
cout < < "Please wait... ";
和cout < < "\nAll done " < < endl;
是在同一行输出的内容,因此会在5秒后一起输出。
类似的把cout改成printf也是一样的结果。
解决的办法是:
cout < < "Please wait... " < <endl;
或者printf( "Please wait...\n ");
如果一定不要换行则在cout < < "Please wait... ";后加一句:cout.flush();
------解决方案--------------------
int main( )
{
char* pbuffer = new char[1024];
setbuf(stdout, pbuffer);
time_t tm = time( NULL ) + 5;
cout < < "Please wait... ";
while ( time( NULL ) < tm )
;
cout < < "\nAll done " < < endl;
delete pbuffer;
}
------解决方案--------------------
char* pbuffer = new char[1024];
setbuf(stdout, pbuffer);
印象中,block buffer 的缓冲区大小是有特定常量表示的,不是随便一个 1024 的缓冲都可以。