Blocks下的第一个C++程序

 

 

 main.cpp:
#include <iostream>
#include <exception>

using namespace std;

class Test
{
public:
string name;
long id;
bool pass;
public:
void getUser()
{
pass=false;
while(pass==false)
{
try{
pass=true;
cout<<"Input your id:"<<endl;
cin>>id;
if(cin.fail()) //判读输入是不是正确的
{
throw new exception;
}
cout<<"Input your name:"<<endl;
cin>>name;
//下面是不用异常处理方法做的。注意里面的continue,其实这是针对上面cin>>id写的。
if(cin.fail())
{
pass=false;
cin.clear();
cout<<"Your name is wrong,please input again!"<<endl;
continue;
}
}catch(exception* e)//这里要用exception*不然会编译会出错
{
pass=false;
cout<<"Your inputing is wrong,please input again!"<<endl;
cin.clear();//cin.clear()方法很重要,如果不掉用,则cin异常不会终止,那么程序就进入了死循环
delete e;
}
}

}
void display()
{
cout<<"This is my first class processed in linux!"<<endl;
cout<<"my name is "<<name<<endl;
}
};
int main()
{
Test* tt= new Test();
tt->getUser();
tt->display();
return 0;
}

 

    笔记:

    1.注意函数cin.fail()的用处。

    2.注意函数cin.clear()的用法(有注释)。

....................................................................

    3.getUser()这个函数目的是为了检测输入异常。这里可以是一个c++中异常处理的实例,网上很多人士说建议不要使用c++中的异常处理机制,不知道什么原因。所以我就在cin>>name下面实现了不用异常处理的方法,但是写的代码比较多。同时,这个方法处理完输入异常后会做一个循环,直到你输入正确的内容。

【责编:ben】
 

详细请点击:http://www.verydemo.com/demo_c92_i281669.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值