计算机二级:Blocks下的第一个C 程序计算机二级考试
文章作者 100test 发表时间 2009:04:30 05:23:53
来源 100Test.Com百考试题网
2009年下半年全国计算机等级考试你准备好了没?考计算机等级考试的朋友,2009年下半年全国计算机等级考试时间是2009年9月19日至23日。更多优质资料尽在百考试题论坛 百考试题在线题库
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异常不会终止,那么程序就进入了死循环
0delete 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.注意catch中的exception*.
3.getUser()这个函数目的是为了检测输入异常。这里可以是一个c 中异常处理的实例,网上很多人士说建议不要使用c 中的异常处理机制,不知道什么原因。所以我就在cin>.>.name下面实现了不用异常处理的方法,但是写的代码比较多。同时,这个方法处理完输入异常后会做一个循环,直到你输入正确的内容。