Reputation: 4397
Let's say I have some structure, for example a Rectangle
:
struct Rectangle
{
int x0, x1, y0, y1;
};
Is it possible to create a Rectangle struct in a way to be able to just call:
Rectangle rec;
cin >> rec;
? I think it should be possible to make it somehow, but I am not experienced enough.
Disclaimer
I am not looking for this:
cin >> rec.x0 >> rec.x1 >> rec.y0 >> rec.y1;
Upvotes: 1
Views: 103
Reputation: 12068
Yes, the best solution is to overload operator>>
for Rectangle
:
struct Rectangle
{
int x0, x1, y0, y1;
};
istream& operator>>(istream& s, Rectangle& r)
{
s >> r.x0 >> r.x1 >> r.y0 >> r.y1;
return s;
}
Upvotes: 4
Reputation: 206667
You can use:
Rectangle rec;
cin >> rec;
if you define an appropriate operator>>
function.
std::istream& operator>>(std::istream& in, Rectangle& rec)
{
return (in >> rec.x0 >> rec.x1 >> rec.y0 >> rec.y1);
}
If you are not allowed to define such a function, then you cannot use the syntax you want to use.
Upvotes: 10