C++ 中cerr和cout的区别实例详解

所属分类: 软件编程 / C 语言 阅读数: 81
收藏 0 赞 0 分享

C++ 中cerr和cout的区别实例详解

前言:

 cerrThe object controls unbuffered insertions to the standard error output as a byte stream. Once the object is nstructed, the expression cerr.flags & unitbuf is nonzero.

  Example

 // iostream_cerr.cpp
// compile with: /EHsc
// By default, cerr and clog are the same as cout
#include <iostream>
#include <fstream>
 
using namespace std;
 
void TestWide( ) 
{
 int i = 0;
 wcout << L"Enter a number: ";
 wcin >> i;
 wcerr << L"test for wcerr" << endl;
 wclog << L"test for wclog" << endl; 
}
 
int main( ) 
{
 int i = 0;
 cout << "Enter a number: ";
 cin >> i;
 cerr << "test for cerr" << endl;
 clog << "test for clog" << endl;
 TestWide( );
}
 
 
 Input 
 Sample Output 
Enter a number: 3
test for cerr
test for clog
Enter a number: 1
test for wcerr
test for wclogcout
 
The object controls insertions to the standard output as a byte stream.
 
cerr 
extern ostream cerr; 
The object controls unbuffered insertions to the standard error output as a byte stream. Once the object is constructed, the expression cerr.flags() & unitbuf is nonzero. 
 
cout 
extern ostream cout; 
The object controls insertions to the standard output as a byte stream.
 

cerr: 错误输出流,无缓冲,不可以重定向。输出的数据不经过缓冲区,直接放到指定的目标中,既然不经过缓冲区那么其它程序就无法把要输出的内容送到其他目标中,所以说它不能被重定向。 

cout:标准输出流,有缓冲,可重定向。把要输出的数据先放到缓冲区中,然后再从缓冲区到你指定的设备中。当向cout流插入一个endl,不论缓冲区是否漫了,都立即输出流中所有数据,然后插入一个换行符. 

注:Linux下可以用标准错误输出间接重定向cerr的输出

如有疑问请留言或者到本站社区交流讨论,感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

更多精彩内容其他人还在看

C++ COM编程之接口背后的虚函数表

这篇文章主要介绍了C++ COM编程之接口背后的虚函数表,COM的背后,就是接口,而接口的背后,就是虚函数表,需要的朋友可以参考下
收藏 0 赞 0 分享

C++设计模式之装饰模式

这篇文章主要介绍了C++设计模式之装饰模式,装饰模式能够实现动态的为对象添加功能,是从一个对象外部来给对象添加功能,需要的朋友可以参考下
收藏 0 赞 0 分享

C++ COM编程之QueryInterface函数(一)

这篇文章主要介绍了C++ COM编程之QueryInterface函数(一),QueryInterface是组件本身提供对自己查询的一个接口,需要的朋友可以参考下
收藏 0 赞 0 分享

C++ COM编程之QueryInterface函数(二)

这篇文章主要介绍了C++ COM编程之QueryInterface函数(二),本文是第二篇,第一篇请参阅相关文档,需要的朋友可以参考下
收藏 0 赞 0 分享

C++中的类型转换static_cast、dynamic_cast、const_cast和reinterpret_cast总结

这篇文章主要介绍了C++中的类型转换static_cast、dynamic_cast、const_cast和reinterpret_cast总结,需要的朋友可以参考下
收藏 0 赞 0 分享

C++设计模式之外观模式

这篇文章主要介绍了C++设计模式之外观模式,本文详细讲解了C++中的Facade模式,并给出了实例代码,需要的朋友可以参考下
收藏 0 赞 0 分享

C++构造函数初始化顺序详解

这篇文章主要介绍了C++构造函数初始化顺序详解,是对C++代码的运行机制深入探讨,需要的朋友可以参考下
收藏 0 赞 0 分享

C++交换指针实例

这篇文章主要介绍了C++交换指针实例,针对C与C++交换指针的方法进行了较为详细的对比分析,非常具有实用价值,需要的朋友可以参考下
收藏 0 赞 0 分享

基于C++实现的线程休眠代码

这篇文章主要介绍了基于C++实现的线程休眠代码,包括了Linux平台及基于boost库的两种实现方法,有不错的参考借鉴价值,需要的朋友可以参考下
收藏 0 赞 0 分享

C++常用字符串分割方法实例汇总

这篇文章主要介绍了C++常用字符串分割方法实例汇总,包括了strtok函数、STL、Boost等常用的各类字符串分割方法,非常具有实用价值,需要的朋友可以参考下
收藏 0 赞 0 分享
查看更多