C++异常处理与输入输出
文章目录
1. C++异常处理
1.1 使用简单的错误分支处理abort()和exit()
int cal(int x, int y){
if(y!=0){
return x/y;
}else{
abort();//直接终止程序,后续代码不再执行
//exit(false);//直接退出程序
}
return -1;
}
1.2 使用try-throw-catch处理机制
double cal(double x,double y){
if(y!=0)
return x/y;
throw "error!";//将异常对象抛出,丢给catch异常处理程序,即直接让程序跳转到catch代码处
}
int main(){
double a,b,c;
while(cin>>a>>b){
try{//如果存在异常,并使用throw抛出后,直接执行catch;如果没有异常,则直接跳过catch执行 //后一条语句
double c=cal(a,b);
}catch(const char *s){//捕获异常对象,并采取相应的措施
cout<<s<<"\n";
cout<<"please input again!"<<"\n";
continue;
}
cout<<"c="<<c<<"\n";
break;
}
cout<<"success!";
}
//使用throw抛出异常对象,执行相应的catch
Student s;
Person p;
throw s;//直接抛给第一个catch
throw p;//直接抛给第二个catch
catch(Student &c_s){...}
catch(Person &c_p){...}
1.3使用exception类,头文件exception
class Student:public exception{
...
}
class Leader:public exception{
...
}
catch(exception &e){
...
}//可以同时捕获Leader及Student基类异常
2. C++输入与输出
处理输入与输出的原理:从磁盘先读取数据块,至缓存区,之后进行数据处理,加快数据读取速度;;;当键盘输入字符,先预存缓存区,当按下回车键时,立即刷新缓冲区
2.1使用string类的getline()输入字符串
string s;
cin.getline(s,100,':');
getline(s,':');//表示使用‘:’作为输入的边界,会自动调整目标string的大小,使之刚好为存储输入的字符大小
//读取输入流方式与cin.getline相同
2.2控制台的输入与输出操作对象cin与cout,iostream头文件,类ostream,istream
//输出cout 控制符endl--->刷新缓存区,并在输出流中加入一个换行符
//flush--->强制刷新缓存区
int sum;
char s;
while(cin>>s){
sum++;
}
cin.clear();//重新恢复流状态
while(!isspace(cin,get())){
continue;//使用cctype的isspace一值读取到空白为止
}
while(cin.get()!='\n'){
continue;//如果不匹配的输入流不是换行符,直接丢弃,结束本次循环
}
cin>>s;
2.3 文件的输入与输出操作对象infile与outfile,头文件ostream,fstream,类ofstream,ifstream
#include <ostream>
#include <fstream>
using namespace std;
int main(){
ofstream outfile;
outfile.open("test.txt");
outfile<<"使用outfile输入数据到我的test.txt文件";
outfile.close();
ifstream infile;
infile.open("test.txt");
char s[100];
infile>>s;//读取存入字符串数组中
cout<<s;//将字符串数组数据输出
infile.close();
}