Jecho

导航

cout cerr clog

  #include <iostream.h>

  int main()

  {

  cout << "hello world---cout" << endl ;

  cerr << "hello world---cerr" << endl ;

  clog << "hello world---clog" << endl;

  return 0;

  }

  在命令行模式下键入下面的命令:

  test >cout.txt

  运行结果是:

  在生成的cout.txt文件中输出了"hello world---cout"

  同时在显示器上输出了"hello world---cerr", "hello world---clog"

  test 0>cout.txt

  运行结果是:

  在生成的cout.txt文件中没有输出

  同时在显示器上输出了"hello world---cout", "hello world---cerr", "hello world---clog"

  NOTE: 3-9 结果一样

  test 1>cout.txt

  运行结果是:

  在生成的cout.txt文件中输出"hello world---cout"

  同时在显示器上输出了"hello world---cerr", "hello world---clog"

  NOTE: 除去0, 3-9, 2 其他结果一样

  test 2>cout.txt

  运行结果是:

  在生成的cout.txt文件中输出"hello world---cerr", "hello world---clog"

  同时在显示器上输出了"hello world---cout"

  clog流也是标准错误流,作用和cerr一样,区别在于cerr不经过缓冲区,直接向显示器输出信息,而clog中的信息存放在缓冲区,缓冲区满或者遇到endl时才输出.

  对于为什么有cerr和clog

  比如,你的程序遇到调用栈用完了的威胁(无限,没有出口的递归)。

  你说,你到什么地方借内存,存放你的错误信息?

  所以有了cerr。其目的,就是在你最需要它的紧急情况下,还能得到输出功能的支持。

  缓冲区的目的,就是减少刷屏的次数——比如,你的程序输出圣经中的一篇文章。不带缓冲的话,就会每写一个字母,就输出一个字母,然后刷屏。有了缓冲,你将看到若干句子“同时”就出现在了屏幕上(由内存翻新到显存,然后刷新屏幕)。

posted on 2013-05-09 16:50  Jecho  阅读(190)  评论(0编辑  收藏  举报