C ++에서 iostream 헤더의 cout, cerr, clog의 차이점은 무엇입니까? 어느 것을 사용해야합니까?
나는 사이의 차이를 연구 노력 cout
, cerr
그리고 clog
인터넷에 있지만 완벽한 해답을 찾을 수 없습니다. 언제 어떤 것을 사용해야할지 아직 명확하지 않습니다. 누구든지 간단한 프로그램을 통해 나에게 설명하고 어떤 것을 사용해야 할 때 완벽한 상황을 설명 할 수 있습니까?
나는 방문 이 사이트 에 작은 프로그램을 보여줍니다 cerr
및 clog
뿐만 아니라 사용하여 얻을 수있다 이상의 출력을 얻을 cout
. 그래서 나는 각각의 정확한 사용에 대해 혼란 스럽습니다.
stdout
그리고 stderr
둘 다 기본적으로 콘솔 출력을 참조하더라도, 다른 스트림입니다. 그들 중 하나를 리디렉션 (파이핑)해도 (예 :) 다른 하나 program.exe >out.txt
에는 영향을주지 않습니다.
일반적으로 stdout
실제 프로그램 출력에 사용되어야하며 모든 정보와 오류 메시지는에 인쇄되어야합니다 stderr
. 그래야 사용자가 출력을 파일로 리디렉션하는 경우 정보 메시지가 출력 파일이 아닌 화면에 계속 인쇄됩니다.
일반적으로 std::cout
일반 출력, std::cerr
오류 및 std::clog
"로깅"(원하는대로 의미 할 수 있음)에 사용합니다.
가장 큰 차이점은 std::cerr
다른 두 가지처럼 버퍼링되지 않는다는 것입니다.
이전 C stdout
와 관련하여 및 stderr
,에 std::cout
해당하는 stdout
반면 std::cerr
및 std::clog
둘 다에 해당합니다 stderr
( std::clog
버퍼링 된 경우 제외 ).
- 표준 출력에는 cout 을 사용하십시오 .
- 오류를 표시 하려면 cerr 을 사용하십시오 .
- 로깅을 위해 clog 를 사용하십시오 .
표준 출력 스트림 (cout) : 클래스 cout
의 인스턴스입니다 ostream
. cout
일반적으로 디스플레이 화면 인 표준 출력 장치에서 출력을 생성하는 데 사용됩니다. 화면에 표시하는 데 필요한 데이터 cout
는 삽입 연산자 ( <<
)를 사용하여 표준 출력 스트림 ( )에 삽입 됩니다.
버퍼링되지 않은 표준 오류 스트림 (cerr) : cerr
오류를 출력하는 데 사용되는 표준 오류 스트림입니다. 이것은 또한 ostream
클래스 의 인스턴스입니다 . 마찬가지로 cerr
입니다 않은 버퍼 우리는 즉시 오류 메시지를 표시 할 때 사용되도록. 오류 메시지를 저장하고 나중에 표시 할 버퍼가 없습니다.
버퍼링 된 표준 오류 스트림 (clog) : 이것은 또한 ostream
클래스 의 인스턴스이며 오류를 표시하는 데 사용되지만 오류와 cerr
는 달리 먼저 버퍼에 삽입되고 완전히 채워지지 않을 때까지 버퍼에 저장됩니다.
추가 읽기 : 기본 입력 출력 c
이 세 가지 스트림의 차이점은 버퍼링입니다.
- cerr을 사용하면 출력이 플러시됩니다.
- 즉시 (cerr이 버퍼를 사용하지 않기 때문에).
- 막힘으로 출력이 플러시됩니다.
- 현재 기능을 마친 후.
- flush 함수를 명시 적으로 호출합니다.
- 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 objectstderr
, declared in<cstdio>
(30.11.1).5 After the object
cerr
is initialized,cerr.flags() & unitbuf
is nonzero andcerr.tie()
returns&cout
. Its state is otherwise the same as required forbasic_ios<char>::init
(30.5.5.2).
ostream clog;
6 The object
clog
controls output to a stream buffer associated with the objectstderr
, 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
'program tip' 카테고리의 다른 글
지시어 정의의`대체`를 사용하는 방법? (0) | 2020.10.07 |
---|---|
OS X 10.8에서 Caps Lock 키를 Control에 다시 매핑하는 방법은 무엇입니까? (0) | 2020.10.07 |
Postgres JSON 배열에 문자열이 포함되어 있는지 확인 (0) | 2020.10.07 |
Gmail에 2 단계 인증이 설정되어 있으면 이메일 전송이 실패합니다. (0) | 2020.10.07 |
Eloquent-같지 않은 곳 (0) | 2020.10.07 |