当前位置:网站首页>cout/cerr/clog的区别
cout/cerr/clog的区别
2022-07-04 22:37:00 【编程小段】
cout/cerr/clog都是C++提供的标准输出流,那这三个到底有什么区别?
cout: 标准输出流,一般缓冲区满或者程序结束才刷新缓冲区
cerr: 标准输出错误,输出一条语句就会刷新一次缓冲区
clog: 标准输出日志,相对来说刷新缓冲区的频率不高
先看一个简单的例子
#include<iostream>
int main()
{
std::cout << "output to cout";
std::cerr << "output to cerr";
std::clog << "output to clog";
}
如果我们直接运行该程序,那么这三行都会输出到屏幕
但是,如果我们进行输出重定向,那么cout和cerr/clog会输出到不同的文件(0表示标准输入,1表示标准输出,2表示标准错误输出)
那么,既然有了cerr,为什么还要有clog?
我们都知道程序输入输出都会有缓冲区,缓冲区是在内存中,而文件则是在磁盘中,程序访问内存的速度远快于访问磁盘的速度。所以为了提升效率,程序都会先输出到缓冲区,等缓冲区满了或者在显示刷新缓冲区的时候才会写入到磁盘文件里。但是如果缓冲区还没有满,此时程序崩溃,那么缓冲区中的数据就会丢失,相对来说cerr错误信息就会很重要,为了保证错误信息写入到磁盘文件,程序会经常刷新缓冲区。clog日志信息相对来说就没有那么重要,因此也不会经常刷新缓冲区(注意:频繁的刷新缓冲区会降低运行速度,因为频繁的访问磁盘内容)
std::flush:刷新缓冲区
std::endl:刷新缓冲区并且换行
一般的程序会在程序运行结束才会去刷新缓冲区,但是有时我们不想刷新缓冲区但是想加一个换行,那么就要使用转义字符\n
#include<iostream>
int main()
{
std::cout << "output to cout\n";
std::cerr << "output to cerr\n";
std::clog << "output to clog\n";
}

边栏推荐
- 攻防世界 MISC 进阶区 3-11
- A complete tutorial for getting started with redis: understanding and using APIs
- Redis getting started complete tutorial: Geo
- Photoshop批量给不同的图片添加不同的编号
- 攻防世界 MISC 高手进阶区 001 normal_png
- mamp下缺少pcntl扩展的解决办法,Fatal error: Call to undefined function pcntl_signal()
- Redis入门完整教程:HyperLogLog
- Redis入门完整教程:有序集合详解
- 攻防世界 MISC 进阶区 can_has_stdio?
- 小程序vant tab组件解决文字过多显示不全的问题
猜你喜欢

JS 3D explosive fragment image switching JS special effect

Analysis of the self increasing and self decreasing of C language function parameters

攻防世界 MISC 进阶区 3-11

Redis入门完整教程:HyperLogLog

Redis getting started complete tutorial: Key Management

A complete tutorial for getting started with redis: redis shell
![[sword finger offer] questions 1-5](/img/54/b70d5290978e842939db99645c6ada.png)
[sword finger offer] questions 1-5

攻防世界 MISC 高手进阶区 001 normal_png
页面关闭前,如何发送一个可靠请求

Redis getting started complete tutorial: hash description
随机推荐
【剑指offer】1-5题
Attack and defense world misc advanced area ditf
Sword finger offer 68 - I. nearest common ancestor of binary search tree
Redis的持久化机制
Explanation of bitwise operators
Summary of index operations in mongodb
Duplicate ADMAS part name
Redis入门完整教程:事务与Lua
Attack and defense world misc advanced zone 2017_ Dating_ in_ Singapore
Unity Xiuxian mobile game | Lua dynamic sliding function (specific implementation of three source codes)
模拟摇杆控制舵机
云服务器设置ssh密钥登录
【二叉树】节点与其祖先之间的最大差值
Mongodb aggregation operation summary
Redis: redis configuration file related configuration and redis persistence
Three stage operations in the attack and defense drill of the blue team
vim编辑器知识总结
Redis入门完整教程:键管理
Common methods in string class
剑指Offer 68 - II. 二叉树的最近公共祖先