• IO流(1)



    #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;
    }

  • 相关阅读:
    js 日期
    二级导航 css
    ajax 输出json数据
    三列板块 css效果
    随机18个数 js
    js 表单非空验证
    ajax案例,调用XML文件
    :hover 鼠标悬浮时(基本导航)
    下载html5-boilerplate(通过npm)
    鼠标滚动,导航置顶.纯css3的position: sticky;
  • 原文地址:https://www.cnblogs.com/w413133157/p/1666798.html
Copyright © 2020-2023  润新知