ostream类的3个输出流对象cout,cerr,clog区别和使用

ostream类定义了3个输出流对象:cout,cerr,clog

cerrclog都是标准错误流,其区别是:cerr不经过缓冲区直接向显示器输出信息;clog中的信息存放在缓冲区,缓冲区满后或遇endl向显示器输出。

例:求解一元二次方程,若公式出错,用cerr流输出有关信息。

:程序:

#include<iostream>

#include<cmath>

using namespace std;


int main()

{

float a, b, c, disc;

cout << "please input a,b,c:";

cin >> a >> b >> c;

if (a == 0)

{

cerr << "a is equal to zero,error!" << endl;

}

else if ((disc = b*b - 4*a*c) < 0)

{

cerr << "disc = b*b - 4*a*c< 0,error!" << endl;

}

else

{

cout << "x1=" << (-b + sqrt(disc)) / (2 * a) << endl;

cout << "x2=" << (-b - sqrt(disc)) / (2 * a) << endl;

}

system("pause");

return 0;

}

运行结果1

please input a,b,c:0 2 3

a is equal to zero,error!

请按任意键继续. . .

运行结果2

please input a,b,c:5 2 3

disc = b*b - 4*a*c< 0,error!

请按任意键继续. . .

运行结果3

please input a,b,c:1 2.5 1.5

x1=-1

x2=-1.5

请按任意键继续. . .