C+++におけるcerrとcoutの違いの実例について詳しく説明する。

2034 ワード

C+++におけるcerrとcoutの違いの実例について詳しく説明する。
前言:
 cerrThe object controls unbuffered insertions to the standarerror out put as a byte stream.Onese the object is nstructed,the expression cerr.flags&unitbuf is nonze.
  Example

 // iostream_cerr.cpp
// compile with: /EHsc
// By default, cerr and clog are the same as cout
#include <iostream>
#include <fstream>
 
using namespace std;
 
void TestWide( ) 
{
 int i = 0;
 wcout << L"Enter a number: ";
 wcin >> i;
 wcerr << L"test for wcerr" << endl;
 wclog << L"test for wclog" << endl; 
}
 
int main( ) 
{
 int i = 0;
 cout << "Enter a number: ";
 cin >> i;
 cerr << "test for cerr" << endl;
 clog << "test for clog" << endl;
 TestWide( );
}
 
 

 Input 
 Sample Output 
Enter a number: 3
test for cerr
test for clog
Enter a number: 1
test for wcerr
test for wclogcout
 
The object controls insertions to the standard output as a byte stream.
 
cerr 
extern ostream cerr; 
The object controls unbuffered insertions to the standard error output as a byte stream. Once the object is constructed, the expression cerr.flags() & unitbuf is nonzero. 
 
cout 
extern ostream cout; 
The object controls insertions to the standard output as a byte stream.
 
cerr:エラー出力ストリーム、バッファなしでリダイレクトできません。出力されたデータはバッファを経ずに指定されたターゲットに直接入れます。バッファを通過しないと他のプログラムは出力するコンテンツを他のターゲットに送ることができないので、リダイレクトされないということです。 
cout:標準出力ストリームは、バッファがあり、リダイレクトできます。出力するデータをバッファに入れてから、バッファから指定されたデバイスに送ります。coutストリームにendlを挿入すると、バッファエリアが拡散しているかどうかにかかわらず、ストリーム内のすべてのデータを出力し、改行符を挿入します。 
注:Linuxでは、間接リダイレクトcerrの出力を標準エラーで出力できます。
疑問があれば、メッセージをお願いします。あるいは、当駅のコミュニティで交流して討論してください。ありがとうございます。