as question says, i want to write custom data type data of a class maybe to a file using ifstream in c++. Need help.
Asked
Active
Viewed 2,302 times
1

stakx - no longer contributing
- 83,039
- 20
- 168
- 268

NativeCoder
- 1,033
- 1
- 10
- 16
-
4You want to write to an ifstream? Admittedly my C++ is a bit rusty, but that doesn't seem possible. – Ignacio Vazquez-Abrams May 02 '10 at 09:01
-
Yep, you'd need either an `ofstream` or a `fstream`. – stakx - no longer contributing May 02 '10 at 09:25
1 Answers
7
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";
}

Marcelo Cantos
- 181,030
- 38
- 327
- 365
-
1+1. The only thing I'd like to add is that if one doesn't want a public `write` method in the class itself, one could declare the global overloaded `operator <<` (the _inserter_) as `friend` inside the class and then either make `write` private, or move its code directly into the inserter. – stakx - no longer contributing May 02 '10 at 09:24
-
Thank you for suggestion, @stakx. I used to code it up as a `friend` without a `write`, but found that it was tedious to write `point.`. I must admit that I never considered the private `write` option. I guess once you decide to use a `friend`, the repeated prefix is less effort than a private `write`. – Marcelo Cantos May 02 '10 at 09:49
-
In fact, I find your solution very clean and a public `write` certainly doesn't hurt, esp. as it communicates to another developer that a `<<` inserter is probably available for that class, too. I am personally no big friend of `friend` but thought it needed to be mentioned for completeness' sake. ;) – stakx - no longer contributing May 02 '10 at 10:03
-
1there is a mistake here. write should be declared as const. std::ostream& write(std::ostream& os) const – Alexei Polkhanov Dec 23 '13 at 03:43