#include "stdafx.h"
#include <iostream.h>
#include <string.h>
#include <strstrea.h>

class Student
{
public:
    Student(const char *pStr,int nAge = 20) : m_nAge(nAge)
    {
        if ( pStr == NULL )
        {
            //
抛出本类异常
            throw ZeroPtr();
        }
        strcpy(m_szName, pStr);
    }
    //
输入输出重载
    friend ostream &operator<<(ostream &Out, const Student &Obj);
    friend istream &operator>>(istream &In, Student &Obj);
private:
    char m_szName[10];
    int  m_nAge;
public:
    class ZeroPtr
    {
    };
};

ostream &operator<<(ostream &Out, const Student &Obj)
{
    Out << Obj.m_szName << endl;
    Out << Obj.m_nAge << endl;
    return Out;
}

istream &operator>>(istream &In, Student &Obj)
{
    In.get(Obj.m_szName, sizeof(Obj.m_szName), '\n');
    In.ignore(256, '\n');
    In >> Obj.m_nAge;
    In.ignore(256, '\n');
    return In;
}  

void FunStr()
{
    char szBuff[256] = {0};
    //
输入流类
    istrstream istr("Hello",0);
    istr >> szBuff;
    //
输出流类
    ostrstream outstr;
    outstr << "Hello" << ends;
   
    cout << outstr.str() << endl;
    memset(outstr.str(),0,strlen(outstr.str()) +sizeof(char));
   
    //
如果还需要赋值,将指针移动到开始处
    outstr.seekp(0, ios::beg);
    //
这里放不下那么长的
    outstr << "Wolrdabsdfewr" << ends;
    //
显示乱码
    cout << outstr.str() << endl;
   
    char ch = 'A';
    outstr.put(ch);
}

int main(int argc, char* argv[])
{
    try
    {
        Student stu(NULL);
       
        cin >> stu ;
        cout << stu << endl;
    }
    catch (Student::ZeroPtr)
    {
        cout << "
异常错误 ZeroPtr" << endl;
    }
    catch (...)
    {
        cout << "
异常错误" << endl;
    }
    return 0;
}

void Fun()
{
    int i,j;
    cin >> i;
    char szString[10];
    //
不安全的写法,容易溢出
    cin >> szString;
    cin.get(szString,10,'5');
    cin.ignore(256,'\n');
    cin >> j;
    cout << i << endl;
    cout << j << endl;
}

posted on 2010-02-09 20:51  o无尘o  阅读(237)  评论(0编辑  收藏  举报