Blocks下的第一個(gè)C++程序

字號(hào):

main.cpp:
    #include
    #include
    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:"<    cin>>id;
    if(cin.fail()) //判讀輸入是不是正確的
    {
    throw new exception;
    }
    cout<<"Input your name:"<    cin>>name;
    //下面是不用異常處理方法做的。注意里面的continue,其實(shí)這是針對(duì)上面cin>>id寫(xiě)的。
    if(cin.fail())
    {
    pass=false;
    cin.clear();
    cout<<"Your name is wrong,please input again!"<    continue;
    }
    }catch(exception* e)//這里要用exception*不然會(huì)編譯會(huì)出錯(cuò)
    {
    pass=false;
    cout<<"Your inputing is wrong,please input again!"<    cin.clear();//cin.clear()方法很重要,如果不掉用,則cin異常不會(huì)終止,那么程序就進(jìn)入了死循環(huán)
    delete e;
    }
    }
    }
    void display()
    {
    cout<<"This is my first class processed in linux!"<    cout<<"my name is "<    }
    };
    int main()
    {
    Test* tt= new Test();
    tt->getUser();
    tt->display();
    return 0;
    }
    考試大提示:
    1.注意函數(shù)cin.fail()的用處。
    2.注意函數(shù)cin.clear()的用法(有注釋?zhuān)?BR>    3.注意catch中的exception*。
    3.getUser()這個(gè)函數(shù)目的是為了檢測(cè)輸入異常。這里可以是一個(gè)c++中異常處理的實(shí)例,網(wǎng)上很多人士說(shuō)建議不要使用c++中的異常處理機(jī)制,不知道什么原因。所以我就在cin>>name下面實(shí)現(xiàn)了不用異常處理的方法,但是寫(xiě)的代碼比較多。同時(shí),這個(gè)方法處理完輸入異常后會(huì)做一個(gè)循環(huán),直到你輸入正確的內(nèi)容。