当前位置:网站首页>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";
}
边栏推荐
- Redis入门完整教程:Bitmaps
- S32 Design Studio for ARM 2.2 快速入门
- Editplus-- usage -- shortcut key / configuration / background color / font size
- 常用技术指标之一文读懂BOLL布林线指标
- Analysis of the self increasing and self decreasing of C language function parameters
- Unity Xiuxian mobile game | Lua dynamic sliding function (specific implementation of three source codes)
- LabVIEW中比较两个VI
- Sword finger offer 67 Convert a string to an integer
- MP进阶操作: 时间操作, sql,querywapper,lambdaQueryWapper(条件构造器)快速筛选 枚举类
- Analysis of environmental encryption technology
猜你喜欢
JS 3D explosive fragment image switching JS special effect
MySQL Architecture - logical architecture
[graph theory] topological sorting
【二叉树】节点与其祖先之间的最大差值
The small program vant tab component solves the problem of too much text and incomplete display
Attack and defense world misc advanced zone 2017_ Dating_ in_ Singapore
Attack and defense world misc advanced area Hong
Redis入门完整教程:Bitmaps
Set up a website with a sense of ceremony, and post it to 1/2 of the public network through the intranet
页面关闭前,如何发送一个可靠请求
随机推荐
How to send a reliable request before closing the page
One of the commonly used technical indicators, reading boll Bollinger line indicators
The small program vant tab component solves the problem of too much text and incomplete display
Is Huatai Securities a nationally recognized securities firm? Is it safe to open an account?
Attack and defense world misc master advanced zone 001 normal_ png
ECS settings SSH key login
攻防世界 MISC 进阶区 hit-the-core
JS 3D explosive fragment image switching JS special effect
云服务器设置ssh密钥登录
Feature scaling normalization
Redis入门完整教程:HyperLogLog
剑指 Offer 68 - I. 二叉搜索树的最近公共祖先
Attack and defense world misc advanced grace-50
Serial port data frame
攻防世界 MISC 进阶区 can_has_stdio?
[OpenGL] note 29 anti aliasing (MSAA)
Analog rocker controlled steering gear
Summary of wechat applet display style knowledge points
The difference between Max and greatest in SQL
[Lua] Int64 support