c ++中iostream头的cout,cerr,clog有什么区别?什么时候用哪一种?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16772842/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 20:38:05  来源:igfitidea点击:

What is the difference between cout, cerr, clog of iostream header in c++? When to use which one?

c++iostreamcoutclog

提问by Arlene Batada

I tried researching the difference between cout, cerrand clogon the internet but couldn't find a perfect answer. I still am not clear on when to use which. Can anyone explain to me, through simple programs and illustrate a perfect situation on when to use which one?

我尝试在互联网上研究cout,cerr和之间的区别,clog但找不到完美的答案。我仍然不清楚什么时候使用哪个。任何人都可以通过简单的程序向我解释并说明何时使用哪个的完美情况?

I visited this sitewhich shows a small program on cerrand clog, but the output obtained over there can also be obtained using cout. So, I'm confused over each one's exact use.

我访问了这个站点,它在cerr和上显示了一个小程序clog,但是在那里获得的输出也可以使用cout. 所以,我对每个人的确切用途感到困惑。

采纳答案by riv

stdoutand stderrare different streams, even though they both refer to console output by default. Redirecting (piping) one of them (e.g. program.exe >out.txt) would not affect the other.

stdoutstderr是不同的流,即使它们默认都指向控制台输出。重定向(管道)其中一个(例如program.exe >out.txt)不会影响另一个。

Generally, stdoutshould be used for actual program output, while all information and error messages should be printed to stderr, so that if the user redirects output to a file, information messages are still printed on the screen and not to the output file.

通常,stdout应该用于实际程序输出,而所有信息和错误消息都应该打印到stderr,这样如果用户将输出重定向到文件,信息消息仍然打印在屏幕上而不是输出文件。

回答by Some programmer dude

Generally you use std::coutfor normal output, std::cerrfor errors, and std::clogfor "logging" (which can mean whatever you want it to mean).

通常,您std::cout用于正常输出、std::cerr错误和std::clog“记录”(这可以意味着您想要的任何含义)。

The major difference is that std::cerris not buffered like the other two.

主要区别在于它std::cerr不像其他两个那样被缓冲。



In relation to the old C stdoutand stderr, std::coutcorresponds to stdout, while std::cerrand std::clogboth corresponds to stderr(except that std::clogis buffered).

相对于旧的 C stdoutand stderrstd::cout对应于stdout,whilestd::cerrstd::clogboth 对应于stderr(除了std::clog被缓冲的)。

回答by roottraveller

Standard output stream (cout):coutis the instance of the ostreamclass. coutis used to produce output on the standard output device which is usually the display screen. The data needed to be displayed on the screen is inserted in the standard output stream (cout) using the insertion operator (<<).

标准输出流(cout):coutostream类的实例。cout用于在标准输出设备(通常是显示屏)上产生输出。需要在屏幕上显示的数据cout使用插入运算符 ( <<)插入到标准输出流( ) 中。

Un-buffered standard error stream (cerr):cerris the standard error stream which is used to output the errors. This is also an instance of the ostreamclass. As cerris un-bufferedso it is used when we need to display the error message immediately. It does not have any buffer to store the error message and display later.

未缓冲的标准错误流 (cerr):cerr是用于输出错误的标准错误流。这也是ostream类的一个实例。由于cerr未缓冲的所以当我们需要立即显示错误消息则使用它。它没有任何缓冲区来存储错误消息并稍后显示。

Buffered standard error stream (clog):This is also an instance of ostreamclass and used to display errors but unlike cerrthe error is first inserted into a bufferand is stored in the buffer until it is not fully filled.

缓冲标准错误流(clog):这也是ostream类的一个实例,用于显示错误,但与错误不同cerr的是,错误首先插入缓冲区并存储在缓冲区中,直到它没有完全填满。

further reading : basic-input-output-c

进一步阅读:基本输入输出-c

回答by Duc-Viet Ha

The difference of these 3 streams is buffering.

这 3 个流的区别在于缓冲。

  1. With cerr, the output flushs
    • immediately (because cerr does not use buffer).
  2. With clog, the output flushs
    • after you finish your current function.
    • explicitly call the function flush.
  3. With cout, the output flushs
    • after you have call to any output streams (cout, cerr, clog).
    • after you finish your current function.
    • explicitly call the function flush.
  1. 使用 cerr,输出刷新
    • 立即(因为 cerr 不使用缓冲区)。
  2. 随着堵塞,输出冲洗
    • 完成当前功能后。
    • 显式调用函数flush。
  3. 使用 cout,输出刷新
    • 在您调用任何输出流(cout、cerr、clog)之后。
    • 完成当前功能后。
    • 显式调用函数flush。

Please check the following code, and run DEBUG through 3 lines: f(std::clog), f(std::cerr), f(std::out), then open 3 output files to see what happened. You can swap these 3 lines to see what will happen.

请检查以下代码,并通过 3 行运行 DEBUG:f(std::clog)、f(std::cerr)、f(std::out),然后打开 3 个输出文件以查看发生了什么。您可以交换这 3 行,看看会发生什么。

#include <iostream>
#include <fstream>
#include <string>

void f(std::ostream &os)
{
    std::cin.clear(); // clear EOF flags
    std::cin.seekg(0, std::cin.beg); // seek to begin

    std::string line;
    while(std::getline(std::cin, line))   //input from the file in.txt
        os << line << "\n";   //output to the file out.txt
}

void test()
{
    std::ifstream in("in.txt");
    std::ofstream out("out.txt"), err("err.txt"), log("log.txt");
    std::streambuf *cinbuf = std::cin.rdbuf(), *coutbuf = std::cout.rdbuf(), *cerrbuf = std::cerr.rdbuf(),
                    *clogbuf = std::clog.rdbuf();

    std::cin.rdbuf(in.rdbuf()); //redirect std::cin to in.txt!
    std::cout.rdbuf(out.rdbuf()); //redirect std::cout to out.txt!
    std::cerr.rdbuf(err.rdbuf());
    std::clog.rdbuf(log.rdbuf());


    f(std::clog);
    f(std::cerr);
    f(std::cout);

    std::cin.rdbuf(cinbuf);
    std::cout.rdbuf(coutbuf);
    std::cerr.rdbuf(cerrbuf);
    std::clog.rdbuf(clogbuf);
}

int main()
{
    test();
    std::cout << "123";
}

回答by David Vargas

  • Use coutfor the standard output.
  • Use cerrto show errors.
  • Use clogfor logging.
  • 使用cout作为标准输出。
  • 使用cerr显示错误。
  • 使用clog进行日志记录。

回答by Tony Delroy

From a draft C++17 standard document:

来自 C++17 标准文档草案:

30.4.3 Narrow stream objects [narrow.stream.objects]

istream cin;

1 The object cincontrols input from a stream buffer associated with the object stdin, declared in <cstdio>(30.11.1).

2 After the object cinis initialized, cin.tie()returns &cout. Its state is otherwise the same as required for basic_ios<char>::init(30.5.5.2).

ostream cout;

3 The object coutcontrols output to a stream buffer associated with the object stdout, declared in <cstdio>(30.11.1).

ostream cerr;

4 The object cerrcontrols output to a stream buffer associated with the object stderr, declared in<cstdio>(30.11.1).

5 After the object cerris initialized, cerr.flags() & unitbufis nonzero and cerr.tie()returns &cout. Its state is otherwise the same as required for basic_ios<char>::init(30.5.5.2).

ostream clog;

6 The object clogcontrols output to a stream buffer associated with the object stderr, declared in <cstdio>(30.11.1).

30.4.3 窄流对象 [narrow.stream.objects]

istream cin;

1 对象cin控制来自与对象关联的流缓冲区的输入stdin,在<cstdio>(30.11.1) 中声明。

2 对象cin初始化后,cin.tie()返回&cout。它的状态在其他方面与basic_ios<char>::init(30.5.5.2)要求的相同。

ostream cout;

3 对象cout控制输出到与对象关联的流缓冲区stdout,在<cstdio>(30.11.1) 中声明。

ostream cerr;

4 对象cerr控制输出到与对象关联的流缓冲区stderr,在<cstdio>(30.11.1) 中声明。

5 对象cerr初始化后,cerr.flags() & unitbuf非零并cerr.tie()返回&cout。它的状态在其他方面与basic_ios<char>::init(30.5.5.2)要求的相同。

ostream clog;

6 对象clog控制输出到与对象关联的流缓冲区stderr,在<cstdio>(30.11.1)中声明。

Discussion...

讨论...

coutwrites to stdout; cerrand clogto stderr

cout写信给stdout; cerrclogstderr

Standard Out (stdout) is intended to receive non-error, non-diagnostic output from the program, such as output from successful processing that can be displayed to the end-user or streamed into some further processing stage.

标准输出 ( stdout) 旨在接收来自程序的非错误、非诊断输出,例如成功处理的输出,可以显示给最终用户或流式传输到某个进一步的处理阶段。

Standard Error (stderr) is intended for diagnostic output, such as warning and error messages that indicate the program hasn't or may not have produced the output the user might expect. This input may be displayed to the end user even if the output data is piped to a further processing stage.

标准错误 ( stderr) 用于诊断输出,例如指示程序没有或可能没有产生用户可能期望的输出的警告和错误消息。即使输出数据被输送到进一步的处理阶段,该输入也可以显示给最终用户。

cinand cerrare tied to cout

cincerrcout

They both flush coutbefore handling I/O operations themselves. This ensures prompts sent to coutare visible before the program blocks to read input from cin, and that earlier output to coutis flushed before writing an error through cerr, which keeps the messages in chronological order of their generation when both are directed to the same terminal/file/etc..

它们都cout在自己处理 I/O 操作之前刷新。这确保发送到的提示cout在程序块读取输入之前是可见的cin,并且cout在写入错误之前刷新较早的输出 to cerr,当两者都被定向到同一个终端/文件/等等..

This contrasts with clog- if you write there it won't be buffered and isn't tied to anything, so it will buffer decent sized amounts of logging before flushing. This yields the highest throughput of messages, but means the messages may not be quickly visible to a would-be consumer reading the terminal or tailing the log.

这与clog- 如果你在那里写它不会被缓冲并且不与任何东西相关联,所以它会在刷新之前缓冲相当数量的日志记录。这产生了最高的消息吞吐量,但意味着消息可能无法快速被潜在消费者读取终端或拖尾日志看到。

回答by Kashif Faraz Shamsi

Both coutand clogare buffered but cerris un-buffered and all of these are predefined objects which are instances of class ostream. The basic use of these three are coutis used for standard input whereas clogand cerris used for showing errors. The main point why cerris un-buffered is may be because suppose you have several outputs in the buffer and an error exception is mentioned in the code then you need to display that error immediately which can be done by cerreffectively.

COUT阻塞被缓冲但CERR是无缓冲和所有的这些预定义其是类ostream的实例的对象。这三个的基本用途是cout用于标准输入,而clogcerr用于显示错误。最主要的一点,为什么CERR是无缓冲IS可能是因为假设你有在缓冲区几个输出和一个错误异常的代码中提到,那么你需要立即显示错误,可以这样做CERR有效。

Please correct me if I am wrong.

如果我错了,请纠正我。

回答by Devendra singh

cout is usually used to display some statements on user screen. ex- : cout<<"Arlene Batada";

cout 通常用于在用户屏幕上显示一些语句。ex- : cout<<"Arlene Batada";

output:

输出:

Arlene Batada

阿琳·巴达达