1
votes

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?

4
Use a couple of if-statements. if (real < 0) etc. Sidenote: Instead of calling the components x and y, it would make more sense to refer to them as real and imaginary, especially since that's what you do when you're speakingbyxor
I'm assuming you're doing this as an exercise or due to lack of required features, if not is worth noting that std::complex exists.Carl
I would suggest to change the title. THe question seems to be about printing the sign rather than complex numbers. If it was the latter using std::complex would be the way to go, and the current title for sure will attract users seeking for how to print std::complex463035818_is_not_a_number

4 Answers

2
votes

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;
}
1
votes

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;
}
0
votes

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 << "+";
}
0
votes

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;