cout,cerr和clog的区别

  • 官方解释:

cout——Standard output stream

Object of class ostream that represents the standard output stream oriented to narrow characters (of type char). It corresponds to the C stream stdout

cerr——Standard output stream for errors

Object of class ostream that represents the standard error stream oriented to narrow characters (of type char). It corresponds to the C stream stderr

clog——Standard output stream for errors

Object of class ostream that represents the standard logging stream oriented to narrow characters (of type char). It corresponds, along with cerr to the C stream stderr

可以看出这三者在C++中都是标准IO库中提供的输出工具,其中

cout:一个ostream对象,向标准输出写入数据;

cerr:一个ostream对象,通常用于输出程序错误信息,写入到标准错误;

clog:也是写入到标准错误,这点和cerr有点儿像,平常很少用到。

  • 三者的区别:

1、cout的输出可以重定向到一个文件中,而cerr必须输出在显示器上

2、cerr不经过缓冲区,直接向显示器输出信息, 而clog中的信息存放在缓冲区内, 缓冲区满或者遇到 endl 时才输出。

  • 那么,为什么要有cerrclog呢?

假设你的程序遇到调用栈用完了的威胁(无限,没有出口的递归),那么到什么地方借内存来存放错误信息?所以有了cerr。其目的,就是在你最需要它的紧急情况下,还能得到输出功能的支持

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

 

 

参考自:https://blog.csdn.net/qq_38556370/article/details/80640845

原文链接: https://www.cnblogs.com/Yanfang20180701/p/10790869.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

    cout,cerr和clog的区别

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/294390

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月15日 下午3:54
下一篇 2023年2月15日 下午3:56

相关推荐