注册 登录
编程论坛 C++教室

[求助]不明白cerr 与cout 的区别

cpluslover 发布于 2007-05-03 19:29, 1334 次点击

今天好象很倒霉的样子

随便在书上看点什么东西 都有会遇到问题

下面是潜能书上的例子,我看不出来这个cerr与 cout
的区别啊

改成cout也运行完全一样

//**********************
//** ch19_1.cpp **
//**********************

#include<iostream.h>

void fn(int a, int b)
{
if(b==0)
cerr <<"zero encountered. "
<<"The message cannot be redirected";
else
cout <<a/b <<endl;
}

void main()
{
fn(20,2);
fn(20,0);
}

请讲一讲啊
先谢谢了

8 回复
#2
aipb20072007-05-03 19:42
cout上标准输出流
cerr是标准错误流


本质上一样的吧,都是ostream,这样不同的定义只是种区分吧!

我这样理解的,不知道是不是真有什么地方不一样,仅做参考哈!
#3
yuyunliuhen2007-05-03 20:25

[QUOTE]cerr
Specifies the cerr global stream.
extern ostream cerr;

Return Value
An ostream object.

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

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
3
1
Sample Output
Copy Code
Enter a number: 3
test for cerr
test for clog
Enter a number: 1
test for wcerr
test for wclog
[/QUOTE]


clog:
extern ostream clog;
The object controls buffered insertions to the standard error output as a byte stream.

cout:The object controls insertions to the standard output as a byte stream.

呵呵,不用翻译了吧,很易懂的。平时多查查MSDN,很有帮助的,对英语也是一种提高哦

[此贴子已经被作者于2007-5-3 20:35:09编辑过]

#4
cpluslover2007-05-03 21:20
我的ENGLISH
有你那么好就好了
#5
zkkpkk2007-05-03 22:19
一样的吧,只不够CERR一般用在错误输出上
#6
leeco2007-05-16 15:52
sample shows everything.

#include <iostream>
using namespace std;

int main()
{
    int a,b;
    freopen(\"in.txt\",\"r\",stdin);
    freopen(\"out.txt\",\"w\",stdout);
    cin>>a>>b;
    if(b!=0){
        cout<<\"a/b=\"<<a/b<<endl;
    }
    else {
        cerr<<\"b can't be zero.\"<<endl;
    }
}

#7
raulxxyuer2007-05-16 16:01

有看过的呀

#8
I喜欢c2007-05-16 17:31

你把cerr和cout换个位子试试....

#9
PcrazyC2007-05-16 17:40
1.cout可以重定向,而cerr不能重定向.只能定向到屏幕

2.cout先储存在缓存区,而cerr没有缓存区,直接输出.
1