Search code examples
c++iostreamfstreaminserter

how to write any custom data type to file using ifstream?


as question says, i want to write custom data type data of a class maybe to a file using ifstream in c++. Need help.


Solution

  • For an arbitrary class, say, Point, here's a fairly clean way to write it out to an ostream.

    #include <iostream>
    
    class Point
    {
    public:
        Point(int x, int y) : x_(x), y_(y) { }
    
        std::ostream& write(std::ostream& os) const
        {
            return os << "[" << x_ << ", " << y << "]";
        }
    
    private:
        int x_, y_;
    
    };
    
    std::ostream& operator<<(std::ostream& os, const Point& point)
    {
        return point.write(os);
    }
    
    int main() {
        Point point(20, 30);
        std::cout << "point = " << point << "\n";
    }