Search code examples
c++operator-overloadingiostreamcinistream

Input streaming for user defined class


For a user defined class I have overloaded << operator in the following way for cout

ostream& operator<<(ostream& os, const myObject& obj_)
{
    if (obj_.somefloat != 0)
        os << "(" << obj_.somefloat << ")";
    else if ( obj_.oneint != 0 && obj_.twoint != 0)
        os << "(" << obj_.oneint << "#" << obj_.twoint << ")";
    else    
        os << "Empty Object";
    return os;
}

How to overload >> operator equivalently for cin


Solution

  • this should work:

    std::istream& operator>>( std::istream& in, myObject& obj_ )
    {
        char c;
        if( in >> c )
        {
            if( c == '(' )
            {
                float f;
                if( in >> f >> c ) // f reads also an int
                {
                    if( c == ')' )  // single float format
                    {
                        if( f != 0.0 )
                            obj_.somefloat = f;
                        else
                            in.setstate( std::ios_base::failbit );
                    }
                    else if( c == '#' ) // two int format
                    {
                        if( float(int(f)) != f  )
                            in.setstate( std::ios_base::failbit );
                        else
                        {
                            obj_.somefloat = 0;
                            obj_.oneint = int(f);
                            if( in >> obj_.twoint >> c && (c != ')' || (obj_.oneint == 0 && obj_.twoint == 0) ) )
                                in.setstate( std::ios_base::failbit );
                        }
                    }
                    else
                        in.setstate( std::ios_base::failbit );
                }
            }
            else if( c == 'E' ) // "Empty Object"
            {
                const char* txt="Empty Object";
                ++txt; // 'E' is already read
                for( ; *txt != 0 && in.get() == *txt && in; ++txt )
                    ;
                if( *txt == char(0) )
                {
                    obj_.somefloat = 0;
                    obj_.oneint = 0;
                    obj_.twoint = 0;
                }
                else
                    in.setstate( std::ios_base::failbit );
            }
            else
                in.setstate( std::ios_base::failbit );
        }
        return in;
    }