Search code examples
c++stdcoutstringstream

How can I make the sign appear at the end of the fill when using std::cout and std::stringstream?


I have the following code for formatting a printout to always be 4 digits with sign included:

std::stringstream pitch; 
pitch.precision(0);

pitch.width(4);
pitch.fill('0');

pitch << std::showpos << (int)(m_values["Pitch_1"]);

I would also like to show the sign ("+"/"-"), but I want it to precede the fill, as follows:

+002

However, the code I have here moves the "+" sign to the most significant digit:

00+2

How, if possible, can I change the formatting so that I have the former, instead of the latter?


Solution

  • Use the std::internal manipulator:

    pitch << std::internal << std::showpos << 5;