作者ric2k1 (Ric)
看板EE_DSnP
标题Re: [请益]请问cout.flush()的功用
时间Thu Oct 2 22:03:23 2008
※ 引述《gn02003330 ()》之铭言:
: 标题: [请益]请问cout.flush()的功用
: 时间: Thu Oct 2 01:14:02 2008
:
: 1.第一题作业的提示有说要用到cout.flush()
: 说是清除缓冲区强制输出
: 请问跟直接用cout输出有什麽不同?
: 因为我没用这个函数也写出"看起来很像"题目指定的结果
:
: 2.真的不用再另外用函数计时吗
: 自己电脑的CPU还不差
: 写出来的时间飙超快的XD
:
: 解答感谢
:
: --
:
※ 发信站: 批踢踢实业坊(ptt.cc)
: ◆ From: 220.136.179.17
: → chicklet:顺便问一下使用方法..不懂 10/02 21:32
不用 cout.flush() 看起来不会很怪吗?
请看 cout.flush() 的定义 (from www.cplusplus.com)
=============================================================================
ostream& flush ( );
Flush output stream buffer
Synchronizes the buffer associated with the stream to its controlled output
sequence. This effectively means that all unwritten characters in the buffer
are written to its controlled output sequence as soon as possible ("flushed").
The function only has meaning for buffered streams, in which case it
effectively calls the pubsync member of the streambuf object
(rdbuf()->pubsync()) associated to the stream.
A manipulator exists with the same name and behavior (see flush manipulator).
=============================================================================
ostream is a buffered stream.
你可以试试以下的程式 (Change the value of "DELAY" to suit the speed of your
computer), 你应该可以看到有东西在 "转":
#include <iostream>
using namespace std;
#define DELAY 20000000
int main()
{
char p[] = { '-', '\\', '|', '/' };
int i = 0;
while (++i) {
cout << p[i % 4];
cout.flush();
for (int j = 0; j < DELAY; j++);
cout << '\b';
}
}
试试看 comment out "cout.flush()" 有何不同?
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 59.121.133.162
1F:→ gn02003330:其实感觉不太出来哪里不一样耶orz,flush应该是把 10/02 23:39
2F:推 saevia:我也觉得差不多... 10/02 23:40
3F:→ gn02003330:buffer里的东西强制清空印出来,所以应该是比较不会 10/02 23:40
4F:→ gn02003330:delay,可是感觉那个delay的时间好像短到根本看不出来 10/02 23:40
5F:推 wintercobra:为什麽要强制清空印出来?cout不就已经印了吗? 10/03 00:18
6F:→ wintercobra:还是说有什麽东西留在缓冲区内? 10/03 00:19
7F:推 timrau:确实可能留在buffer里啊 10/03 01:21
8F:→ timrau:除非碰到换行, 需要input, flush(), 或是buffer full, 10/03 01:22
9F:→ timrau:否则都有可能留在buffer里而没有真的显示出来 10/03 01:23
10F:推 jtes5506:char p[] = ('a','b','c'}这实在太好用啦 一三题都靠他 10/07 08:12
11F:→ jtes5506:by the way 可否指定输入某几项资料,其他空白就好。 10/07 08:14
12F:→ ric2k1:不是很清楚楼上的问题... 不过 array 在下下个章节会教 10/07 08:37