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

  • 相关阅读:
    [py]str list切片-去除字符串首尾空格-递归思想
    [py]python面向对象的str getattr特殊方法
    [py]python多态-动态语言的鸭子类型
    [py]py2自带Queue模块实现了3类队列
    【Unity技巧】制作一个简单的NPC
    java7 新特性 总结版
    【游戏周边】Unity,UDK,Unreal Engine4或者CryENGINE——我应该选择哪一个游戏引擎
    【Unity Shaders】Transparency —— 使用alpha通道创建透明效果
    记录最近的几个bug
    理解WebKit和Chromium: 调试Android系统上的Chromium
  • 原文地址:https://www.cnblogs.com/w413133157/p/1666798.html
Copyright © 2020-2023  润新知