cout和cerr的区别

来源:互联网 发布:线性表c语言实现 编辑:程序博客网 时间:2024/06/05 12:01

问题:

c++中输出通常信息的函数为cout,比如:std::cout << "Hello world";

在异常处理机制中则使用cerr来输出错误信息,比如:std::cerr << "Error: too many arguments\n";

那么,cout和cerr的区别是什么呢?

解决办法:

1. 摘录一段《C++ Primer》第五版P319中关于cout与cerr的区别的描述:
和cout一样,cerr也是一个ostream对象。

它们之间的区别在于:

重定向操作只影响cout,而不影响cerr;

cerr对象仅用于错误消息。

因此,如果将程序输出重定向到文件,并且发生了错误,则屏幕上仍然会出现错误消息。

在UNIX系统中,可以分别对cout和cerr进行重定向,命令行操作符>用于对cout进行重定向,操作符2>对cerr进行重定向。

因为,系统的SHELL里一般约定1为正确流,2为错误流。而1是作为缺省值使用可以省略不写。

2. 示例代码:

# test_cerr.cpp#include <iostream>using namespace std;int main() {    cout << "hello world---cout" << endl ;    cerr << "hello world---cerr" << endl ;    return 0;} 
编译test_cerr.cpp:

g++ test_cerr.cpp -o test_cerr
运行不同的重定向命令:

u1204@u1204-zhw:~/wrk/tmp/cpp_src/cpp_exer$ ./test_cerr 2> test_cerr.txthello world---coutu1204@u1204-zhw:~/wrk/tmp/cpp_src/cpp_exer$ ./test_cerr > test_cout.txthello world---cerru1204@u1204-zhw:~/wrk/tmp/cpp_src/cpp_exer$ cat ./test_cerr.txthello world---cerru1204@u1204-zhw:~/wrk/tmp/cpp_src/cpp_exer$ cat ./test_cout.txt hello world---coutu1204@u1204-zhw:~/wrk/tmp/cpp_src/cpp_exer$