cw901
cw901

Reputation: 11

In C++, can I make cout display doubles as doubles but without touching main()?

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

Answers (2)

Ranoiaetep
Ranoiaetep

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

Jarod42
Jarod42

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

Related Questions