看看大家的基本功,小程序的问题。

GZCompiler 2002-10-31 11:14:53
有以下程序:

#include <iostream.h>
#include <time.h>

void main()
{
time_t tm=time(NULL)+5;
cout<<"Please wait...\n";
while(time(NULL)<tm)
{};
cout<<"End!"<<endl;
}

目的是想在输出"Please wait..."后,等待5秒再输出"End!".
可是实际结果却是一运行程序就先等待五秒,然后两行信息一起输出,程序结束。
谁能尽量准确的解释原因就可以拿到份!
...全文
24 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
GZCompiler 2002-10-31
  • 打赏
  • 举报
回复
结账,献给每个深夜还工作的人!
GZCompiler 2002-10-31
  • 打赏
  • 举报
回复
这是MSDN上的解释:

Title: The Effects of Buffering

The following example shows the effects of buffering. You might expect the program to print please wait, wait 5 seconds, and then proceed. It won’t necessarily work this way, however, because the output is buffered.

#include <iostream.h>
#include <time.h>

void main()
{
time_t tm = time( NULL ) + 5;
cout << "Please wait...";
while ( time( NULL ) < tm )
;
cout << "\nAll done" << endl;
}

To make the program work logically, the cout object must empty itself when the message is to appear. To flush an ostream object, send it the flush manipulator:

cout << "Please wait..." << flush;

This step flushes the buffer, ensuring the message prints before the wait. You can also use the endl manipulator, which flushes the buffer and outputs a carriage return–linefeed, or you can use the cin object. This object (with the cerr or clog objects) is usually tied to the cout object. Thus, any use of cin (or of the cerr or clog objects) flushes the cout object.
GZCompiler 2002-10-31
  • 打赏
  • 举报
回复
这么晚大家还没睡啊,你们回答得都不错,我来总结一下,然后结账。
是要清空缓冲区的,可以使用endl和flush操作:
改成
cout<<"Please wait.."<<endl;

cout<<"Please wait..."<<flush;
都可以。
这就是缓冲区的效果。
ckacka 2002-10-31
  • 打赏
  • 举报
回复
没有清空缓冲区!
用endl是个好习惯,不仅仅是换行,而且清空了缓存!
GOTO_2002 2002-10-31
  • 打赏
  • 举报
回复
C++输出前是将要输出的东西防至缓冲区,然后一起输出。这样就不能按照你的想法输出了。
北极猩猩 2002-10-31
  • 打赏
  • 举报
回复
应该刷新缓冲区,调用cout.flush()刷新
topikachu 2002-10-31
  • 打赏
  • 举报
回复
改成cout<<"Please wait..."<<endl;

原来缓存未清空

24,854

社区成员

发帖
与我相关
我的任务
社区描述
C/C++ 工具平台和程序库
社区管理员
  • 工具平台和程序库社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧