Reputation: 11
quite a specific question but I'm working on an assignment in which I have to use some operator overloads to manipulate some coordinates. The coordinates are doubles but C++ just outputs them as (1,4)
when they're (1.0,4.0)
as they're integers.
I've seen that I can use std::cout.precision
to force cout
to work to 1dp but I'm also not supposed to touch main()
at all in my code.
Could anyone suggest another way?
ostream& operator<<(ostream& OutStream, const Coord& Coordinate)
{
OutStream << "(" << Coordinate.X << "," << Coordinate.Y << ")";
return OutStream;
}
Upvotes: 0
Views: 80
Reputation: 6637
You would do the exact same thing in your operator<<
definition, except changing the name from cout
to whatever ostream
name you've chosen:
ostream& operator<<(ostream& OutStream, const Coord& Coordinate)
{
OutStream.precision(1);
OutStream << "(" << Coordinate.X << "," << Coordinate.Y << ")";
return OutStream;
}
Upvotes: 0
Reputation: 217428
You might add your manipulator in your operator:
ostream& operator<<(ostream& OutStream, const Coord& Coordinate)
{
OutStream << std::fixed << std::setprecision(1)
<< "(" << Coordinate.X << "," << Coordinate.Y << ")";
return OutStream;
}
Upvotes: 2