格式化输出:
cout.width(10),输出宽度10
等效写法:
cout << setw(10) << 123; //需头文件#include<iomanip>
无论哪种写法,都是只对后面一个输出有效.
是用来输出八进制和十六进制常量的前缀,八进制的前缀是0,十六进制常量的前缀是0x;
cout << showbase << 123 << endl;
用来输出小数
cout << showpoint << 1.0;
设置精度
cout << setprecision(2) << 1,0;
异常
catch(…)能够捕获所有类型的异常,但是无法区分出异常的类型,以至于无法输出异常
每个catch只是负责它所对应try块抛出的异常
#include <iostream>
using namespace std;
#include <exception>
class MyType{};
class MyException : public exception{
public:
//throw()意味着这个函数不会抛出异常
const char* what() const throw(){return "My Excrption";}
};
void f()
//这里是个声明,需说明所有可能出现的异常类型
//不声明意味着可能抛出任何类型的异常
//throw()意味着这个函数不会抛出 异常
throw(int, double, const char*, MyType, MyException)
{
cout << "input a num" << endl;
int n;
cin >> n;
if (n==1){throw MyException();}
if (n==2){throw MyType();}
if (n==3){throw "hello";}
if (n==4){throw 2;}
if (n==5){throw 1.2;}
cout << " ==== f() end ===" << endl;
}
int main (){
try{
f();
}
//说明:catch做严格的类型匹配,如果是 char* e 则匹配不到 hello
catch(const char* e){cout << "const char* " << e << endl; }
catch(double e){cout << "double " << e << endl; }
catch(int e){cout << "int " << e << endl; }
//它可以匹配到 MyException e
//catch(exception e){cout << "MyType " << e.what() << endl; }
catch(MyException e){cout << "MyException " << e.what() << endl; }
//其他未知类型异常
catch(...){cout << "... " << "其他类型异常" << endl; }
cout << " ==== main() end ===" << endl;
cin.ignore();
getchar();
return 0;
}