Gilfoyle
Gilfoyle

Reputation: 3636

How to print complex numbers in C++

I am playing around with classes in C++. Currently I am working on a class for complex numbers and want to be able to print them in the following format: -2+3i, 1-4i. That means, that I want the real part to have only a sign if it is negative. In contrast the imaginary part should have always a sign whether it is positive or negative.

I tried the following which did not work as expected:

inline void Complex::print() const {
    std::cout << x;
    std::cout << std::showpos << y << "i" << std::endl;
}

This method prints also for the real part the sign if it is positive. Why does std::showpos affect the first line?

Is there any better way to do that?

Upvotes: 1

Views: 3943

Answers (4)

molbdnilo
molbdnilo

Reputation: 66459

showpos is "sticky", and applies to every following number until it's changed back with noshowpos.

You can use showpos with a local stream to avoid messing with std::cout:

inline void Complex::print() const {
    std::ostringstream y_stream;
    y_stream << showpos << y;
    std::cout << x 
              << y_stream.str() << 'i'
              << std::endl;
}

Upvotes: 2

Abhishek Chandel
Abhishek Chandel

Reputation: 1354

When the showpos format flag is set, a plus sign (+) precedes every non-negative numerical value inserted into the stream (including zeros). This flag can be unset with the noshowpos manipulator.

Minor change in your code:

inline void Complex::print() const {
    std::cout << std::noshowpos << x;
    std::cout << std::showpos << y << "i" << std::endl;
}

Upvotes: 1

Max Vollmer
Max Vollmer

Reputation: 8598

If you never use std::noshowpos, std::cout will keep the showpos flag, so that next time you call print() it affects x (and any other number you ever print with std::cout in your program).

So either use std::noshowpos directly after printing y:

std::cout << std::showpos << y << std::noshowpos << "i" << std::endl;

or directly before printing x:

std::cout << std::noshowpos << x;

Upvotes: 0

Ash Oldershaw
Ash Oldershaw

Reputation: 364

That's because the std::showpos flag affects every number inserted into the stream. (http://www.cplusplus.com/reference/ios/showpos/)

Have you tried using if statements?

if (x > 0)
{
    std::cout << "+";
}

Upvotes: 0

Related Questions