c++中cerr与cout区别

本文详细解析了C++中的标准输出流cout和错误输出流cerr的区别与使用方法,包括它们的缓冲特性、重定向方式及如何在程序中实现这些功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

 

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

 

 

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

 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( );

}

 

 

 

3

1   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.

 

举个小例子: 
  if(OK) 
      cout < < "here!   go   files!\n "; 
  else 
  { 
      cerr   < <   "go   screen!\n "; 
      exit(1); 
    } 
  如果程序的输出被重定向到一个文件,则第一条消息(如果选定)将被发送到文件里,下面的第2条会直接到屏幕。

补充一点:cerr和cout一般默认都是绑定到crt(屏幕)的,区分cout和cerr,就是为了方便重定向,把输出和错误信息分开。 
      重定向可以采用操作系统的标示,如上面的小例子: 
  
      cout < < "here!   go   files!\n "; 
      cerr   < <   "go   screen!\n "; 

    编译为test的话。 
    控制台下执行:   test   >   a.txt 
    则标准输出被重定向到a.txt中,cerr仍在屏幕上。结果就是a.txt   写入了 < "here!   go   files! " 
屏幕打印 "go   screen! "。重定向是操作系统替你完成的。很多时候,这很方便。Linux下很多都是着这种思维。不用自己打开文件,写入,关闭文件哦。 
    此外在C++中也可以在程序内利用streambuf进行重定向。比如: 
      std::ofstream   of( "a.txt "); 
      cout < < "go   screen "; 
      std::cerr.rdbuf(of.rdbuf()); 
      cerr   < <   "here!   go   files!\n "; 
    将完成同样的功能,不过这次不借助操作系统的帮助。 
    注意of关闭后,cerr将不可用。可以先保存再恢复: 
    streambuf*   strm_buffer   =   std::cerr.rdbuf();   //保存 
    ... 
    std::cerr.rdbuf(strm_buffer)   //恢复

unix   下每个进程都默认有三个打开的文件描述符,分别是   STDIN_FILENO(标准输入,一般为0)、STDOUT_FILENO(标准输出,一般为   1)和   STDERR_FILENO(标准错误输出,一般为   2)。在Unix   shell   环境中所有都可以被重定向指向文件、管道和其它流(如   socket)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值