当前位置:网站首页>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";
}
边栏推荐
- Advanced area of attack and defense world misc 3-11
- Redis入门完整教程:有序集合详解
- Erik baleog and Olaf, advanced area of misc in the attack and defense world
- Google collab trample pit
- Create Ca and issue certificate through go language
- 浅聊一下中间件
- [Jianzhi offer] 6-10 questions
- The new version judges the code of PC and mobile terminal, the mobile terminal jumps to the mobile terminal, and the PC jumps to the latest valid code of PC terminal
- ETCD数据库源码分析——处理Entry记录简要流程
- [graph theory] topological sorting
猜你喜欢
The overview and definition of clusters can be seen at a glance
常用技术指标之一文读懂BOLL布林线指标
Analysis of the self increasing and self decreasing of C language function parameters
Redis入门完整教程:慢查询分析
A complete tutorial for getting started with redis: Pipeline
Co create a collaborative ecosystem of software and hardware: the "Joint submission" of graphcore IPU and Baidu PaddlePaddle appeared in mlperf
The small program vant tab component solves the problem of too much text and incomplete display
Redis: redis configuration file related configuration and redis persistence
Set up a website with a sense of ceremony, and post it to 1/2 of the public network through the intranet
MYSQL架构——用户权限与管理
随机推荐
Qt个人学习总结
新版判断PC和手机端代码,手机端跳转手机端,PC跳转PC端最新有效代码
D3.js+Three. JS data visualization 3D Earth JS special effect
Async await used in map
Three stage operations in the attack and defense drill of the blue team
Notepad++ -- editing skills
Redis introduction complete tutorial: List explanation
Persistence mechanism of redis
Lost in the lock world of MySQL
Advanced area of attack and defense world misc 3-11
图片懒加载的原理
ETCD数据库源码分析——处理Entry记录简要流程
[machine learning] handwritten digit recognition
Analysis of environmental encryption technology
Redis getting started complete tutorial: Geo
Sword finger offer 68 - I. nearest common ancestor of binary search tree
Redis入门完整教程:有序集合详解
攻防世界 MISC 进阶区 Ditf
Sword finger offer 68 - ii The nearest common ancestor of binary tree
Common methods in string class