cerr 和 clog 之间的区别
在 C++ 中,输入和输出以字节序列或更通常称为流的形式执行。 cerr 和 clog 都与标准 C 错误输出流 stderr 相关联,但 cerr 是无缓冲的标准错误流,而 clog 是缓冲的标准错误流。在本文中,我们将通过示例详细了解这两个流之间的区别。
cerr:它是用于输出错误的无缓冲标准错误流。这是一个对象 ostream 类类似于cout 。它是无缓冲的,即在需要立即显示错误消息时使用。由于没有缓冲区,因此它无法存储错误消息以供以后显示。因此,只要cerr没有缓冲,它就不能存储消息。
例子:
C++
// c++ program to implement
// the above approach
#include
using namespace std;
// Driver code
int main()
{
cerr << "the message displayed is unbuffered";
return 0;
}
C++
// C++ program to implement
// the above approach
#include
using namespace std;
// Driver code
int main()
{
clog << "the message displayed is buffered";
return 0;
}
输出:
clog:它是缓冲的标准错误流,用于输出错误。这也是类似于cout的ostream类的对象。它被缓冲,即首先将错误消息插入缓冲区,然后将其显示在屏幕上。由于有一个缓冲区,因此它可以存储错误消息以便稍后显示,这与cerr不同。因此,简单地因为clog被缓冲,它不能立即显示消息。 clog通常用于记录目的。对于非关键事件日志记录,效率更重要,因此 clog 优于cerr 。
例子:
C++
// C++ program to implement
// the above approach
#include
using namespace std;
// Driver code
int main()
{
clog << "the message displayed is buffered";
return 0;
}
输出:
差异表: cerr clog 1. It is an unbuffered standard error stream It is a buffered standard error stream 2. It is used for displaying the error. It is used for logging. 3. It is used to display the message immediately. It can not display the message immediately. 4. It can not store the message to display it later. It can store the message in the buffer to display it later. 5. The “c” in cerr refers to “character” and ‘err’ means “error”, Hence cerr means “character error”. The “c” in clog refers to “character” and ‘log’ refers to “logging”, hence clog means “character logging”. 6. It is less efficient than clog because it is unbuffered output. It is more efficient than cerr because it is buffered output. 7. It is preferred for critical errors (errors that can cause system crashes). It is not preferred for critical errors (errors that can cause system crashes).