Search code examples
c++iomanipsetw

align right and left without knowing the string width


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!


Solution

  • 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';