c++7.23

来源:互联网 发布:淘宝发货地址不一样 编辑:程序博客网 时间:2024/06/05 15:41

异常:

异常的最基本模式

try{

待测试语句;

if() //判断语句;

throw 信息; //抛出错误信息

}catch(捕获的错误类型){ //捕获错误信息

 

a; //错误信息处理措施

}

 

模拟一个一层层 错误抛出的函数

#include <iostream>

using namespace std;

struct A{};

funa(int k)

{

if(k==1)

{

cout<<”A1的问题我已经解决了”;

}

if(k==1)

{

cout<<”A2的问题我没办法解决,好像B会解决”;

throw 9.5;

}

if(k==1)

{

cout<<”A3的问题我没办法解决,我也不知道谁能解决先抛出吧”;

throw ‘a’;

}

if(k==1)

{

cout<<”A4的问题我没办法解决,我也不知道谁能解决先抛出吧”;

throw A();

}

 

 

}

funb(int k)

{

try{

funa(k);

}

catch(double)

{

cout<<”B:2类型的问题我已经解决了”<<endl;

}

catch(char)

{

cout<<”B:3类型的问题我可解决不了听说C会呢”<<endl;

throw ‘a’;

}

catch(A)

{

cout<<”C4类型的问题我没办法解决,我也不知道谁能解决先抛出吧”;

throw A();

}

}

func(int k)

{

try{

funb(k);

}

catch(char)

{

cout<<”C3的问题我已经解决了”<<endl;

}

catch(A)

{

cout<<”D4类型的问题我没办法解决,听说主函数会呢”;

throw A();

}

 

 

}

 

int main()

{

try{

func(1);

func(2);

func(3);

func(4); //1,2,3,4 分别代表4中错误类型int ,double.char,结构体;

}catch(A)

{

cout<<”这么简单的错误结构体错误都不会,还是我来解决吧”<<endl;

}

return 0;

}

 

输入输出:

iostream:输入输出流操作;

fstream:文件I/O操作;

strstram;字符串I/O操作;

stdiostream:c c++混合使用头文件;

iomanip 格式化I/O头文件;

 

c++: cin 输入 ,cout输出 cerr错误输出 clog出错输出;

Cstdin输入  stdout输出 stderr错误输出;

 

类比于 C中 一%o等以各种进制形式输出一样,C++中也可以。

int a=10;

cout<<dec<<a<<endl; //10进制输出

cout<<hex<<a<<endl; //16进制输出

cout<<setbase(8)<<endl; //8进制输出 此处要加头文件#include <iomanip>

 

还有很多函数setfill(‘*’),//以‘*’补全剩余字符setw(20) //限制域的长度setprecision(8) 8位精确度,等等,详情见c c++上课发的手册;

put 函数

cout.put(‘a’);即是输出a这个字符,连续输出字符cout.put(‘g’).put(‘o’).put(‘o’).put(‘d’);

cin.get(),从终端得到一个字符,或者字符串。

char a[10];

cin.get(a,10,’\’);    //从终端输入10个字符,以\位结束符。到a数组里面

getline 作用一样。

peek(),观察下一个字符;

putback() 将前面用get或这getline函数从输入流中读取的字符ch返回到输入流,插入到当前指针位置,供后面读取;

ignoro():  cin.ignore(n,终止字符);

 跳过输入流中n个字符,或在遇到指定的终止字符时提前结束。

 :ighore(5,A) //跳过输入流中个字符,遇‘A’后就不再跳了;

 

c++ 文件流操作

#include <iostream>

using namespace std;

struct A{

int num;

char name[20];

int score;

}

int main()

{

fstream a(“hello.txe”,ios::in|ios::out|ios::trunc);

int i;

A b[3]={1,”li”,98,2,”hong”,95,3,”ai”,90};

for(int i=0;i<3;i++)

{

a.outfile<<b[i];

cout<<b[i].name<<b[i].num<<b[i].score<<endl;

}

A c[3];

a.seekg(0,ios::beg);            //把读写位置调到开始位置

for(int i=0;i<3;i++)

{

a.infile>>c[i];

cout<<c[i];

}

return 0;

}