program tip

C ++에서 iostream 헤더의 cout, cerr, clog의 차이점은 무엇입니까?

radiobox 2020. 10. 7. 07:30
반응형

C ++에서 iostream 헤더의 cout, cerr, clog의 차이점은 무엇입니까? 어느 것을 사용해야합니까?


나는 사이의 차이를 연구 노력 cout, cerr그리고 clog인터넷에 있지만 완벽한 해답을 찾을 수 없습니다. 언제 어떤 것을 사용해야할지 아직 명확하지 않습니다. 누구든지 간단한 프로그램을 통해 나에게 설명하고 어떤 것을 사용해야 할 때 완벽한 상황을 설명 할 수 있습니까?

나는 방문 이 사이트 에 작은 프로그램을 보여줍니다 cerrclog뿐만 아니라 사용하여 얻을 수있다 이상의 출력을 얻을 cout. 그래서 나는 각각의 정확한 사용에 대해 혼란 스럽습니다.


stdout그리고 stderr둘 다 기본적으로 콘솔 출력을 참조하더라도, 다른 스트림입니다. 그들 중 하나를 리디렉션 (파이핑)해도 (예 :) 다른 하나 program.exe >out.txt에는 영향을주지 않습니다.

일반적으로 stdout실제 프로그램 출력에 사용되어야하며 모든 정보와 오류 메시지는에 인쇄되어야합니다 stderr. 그래야 사용자가 출력을 파일로 리디렉션하는 경우 정보 메시지가 출력 파일이 아닌 화면에 계속 인쇄됩니다.


일반적으로 std::cout일반 출력, std::cerr오류 및 std::clog"로깅"(원하는대로 의미 할 수 있음)에 사용합니다.

가장 큰 차이점은 std::cerr다른 두 가지처럼 버퍼링되지 않는다는 것입니다.


이전 C stdout관련하여 stderr,에 std::cout해당하는 stdout반면 std::cerrstd::clog둘 다에 해당합니다 stderr( std::clog버퍼링 된 경우 제외 ).


  • 표준 출력에는 cout사용하십시오 .
  • 오류를 표시 하려면 cerr사용하십시오 .
  • 로깅을 위해 clog사용하십시오 .

표준 출력 스트림 (cout) : 클래스 cout의 인스턴스입니다 ostream. cout일반적으로 디스플레이 화면 인 표준 출력 장치에서 출력을 생성하는 데 사용됩니다. 화면에 표시하는 데 필요한 데이터 cout는 삽입 연산자 ( <<)를 사용하여 표준 출력 스트림 ( )에 삽입 됩니다.

버퍼링되지 않은 표준 오류 스트림 (cerr) : cerr 오류를 출력하는 데 사용되는 표준 오류 스트림입니다. 이것은 또한 ostream클래스 의 인스턴스입니다 . 마찬가지로 cerr입니다 않은 버퍼 우리는 즉시 오류 메시지를 표시 할 때 사용되도록. 오류 메시지를 저장하고 나중에 표시 할 버퍼가 없습니다.

버퍼링 된 표준 오류 스트림 (clog) : 이것은 또한 ostream클래스 의 인스턴스이며 오류를 표시하는 데 사용되지만 오류와 cerr달리 먼저 버퍼에 삽입되고 완전히 채워지지 않을 때까지 버퍼에 저장됩니다.

추가 읽기 : 기본 입력 출력 c


이 세 가지 스트림의 차이점은 버퍼링입니다.

  1. cerr을 사용하면 출력이 플러시됩니다.
    • 즉시 (cerr이 버퍼를 사용하지 않기 때문에).
  2. 막힘으로 출력이 플러시됩니다.
    • 현재 기능을 마친 후.
    • flush 함수를 명시 적으로 호출합니다.
  3. cout을 사용하면 출력이 플러시됩니다.
    • 출력 스트림 (cout, cerr, clog)을 호출 한 후.
    • 현재 기능을 마친 후.
    • flush 함수를 명시 적으로 호출합니다.

다음 코드를 확인하고 f (std :: clog), f (std :: cerr), f (std :: out)의 3 줄을 통해 DEBUG를 실행 한 다음 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";
}

초안 C ++ 17 표준 문서에서 :

30.4.3 좁은 스트림 객체 [narrow.stream.objects]

istream cin;

1 객체 cin(30.11.1) stdin에서 선언 된 객체와 관련된 스트림 버퍼의 입력을 제어합니다 <cstdio>.

2 객체 cin가 초기화 된 후를 cin.tie()반환합니다 &cout. 그렇지 않으면 상태는 basic_ios<char>::init(30.5.5.2)에 필요한 것과 동일합니다 .

ostream cout;

3 객체 cout(30.11.1) stdout에서 선언 된 객체와 관련된 스트림 버퍼에 대한 출력을 제어합니다 <cstdio>.

ostream cerr;

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

5 After the object cerr is initialized, cerr.flags() & unitbuf is 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 clog controls output to a stream buffer associated with the object stderr, declared in <cstdio> (30.11.1).

Discussion...

cout writes to stdout; cerr and clog to stderr

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.

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.

cin and cerr are tied to cout

They both flush cout before handling I/O operations themselves. This ensures prompts sent to cout are visible before the program blocks to read input from cin, and that earlier output to cout is 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..

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.


Both cout and clog are buffered but cerr is un-buffered and all of these are predefined objects which are instances of class ostream. The basic use of these three are cout is used for standard input whereas clog and cerr is used for showing errors. The main point why cerr is 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 cerr effectively.

Please correct me if I am wrong.


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

output:

Arlene Batada

참고URL : https://stackoverflow.com/questions/16772842/what-is-the-difference-between-cout-cerr-clog-of-iostream-header-in-c-when

반응형