1

Ok, so I have to make a program with an output that looks like this:

Gross Amount: ............... $3575.00
Federal Tax: ................ $ 536.25
State Tax: .................. $ 125.13
Social Security Tax: ........ $ 205.56
Medicare/Medicaid Tax: ...... $  98.31
Pension Plan: ............... $ 178.75
Health Insurance: ........... $  75.00
Net Pay: .................... $2356.00

The left strings are fixed and I will just type those in, but the totals on the right are variables. I need to find a way to make it where the variables on the right are always set to the right, but there's no way of telling the width(how many digits the total is) of the variable because that is up to the user. All the answers I have seen always treat this as if you know how wide it's going to be. Here's an example:

cout << setw(5) << right << x << endl;  

Every one I find has a number there such as five, but the problem is, I don't know for a fact the width will be five. I want to push the variable to the right no matter what the width of it is. Also, I already have using namespace std; coded, so there's no need for std:: and I have coded #include so I do setw() instead of cout.width()

-----------UPDATE----------

I got it! Thanks guys!

Jesse
  • 25
  • 1
  • 7
  • You usually put a maximum upper-bound value. Do you have any indication of the maximum number of digits to expect? Otherwise I suppose you could always calculate it yourself – Marco A. Sep 14 '15 at 18:50
  • you have to do two passes through the data. once to figure out the max string length necessary, and then another pass to do the output – Marc B Sep 14 '15 at 18:50
  • 1
    Can you wait until you have received all the values before printing them? – Galik Sep 14 '15 at 18:51
  • 1
    Re: `using namespace std;`: https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice – Galik Sep 14 '15 at 18:52
  • I don't have a maximum set, but I don't know if my professor will allow that or not. If I do set a maximum that would fix it because I could just make the setw() the same value as my maximum, right? – Jesse Sep 14 '15 at 19:14

1 Answers1

0

What you want are the adjustfield manipulators. This allows for both left and right justification.

There are three possible settings, internal, left and right.

For example:

std::cout.width( 10 ); std::cout << std::right << v << '\n';

JVene
  • 1,611
  • 10
  • 10