Search code examples
c++couttext-aligniomanipsetw

Another C++ output alignment issue


I've been trying to align the following code for the last 3 hours with zero success. Could anybody fill me in about what I'm doing wrong? My aim is to have the string literal left aligned and the variable right aligned like this:

Loan amount:             $ 10000.00
Monthly Interest Rate:        0.10%

But this is what I keep geting:

Loan amount:             $ 10000.00
Monthly Interest Rate:   0.10%

And this is the most recent version of what I've been trying:

cout << setw(25) << "Loan amount:" << right << "$ "<< amount << endl;
cout << setw(25) << "Monthly Interest Rate:"<< right<< rateMonthly << "%" << endl;

I would really appreciate some help.


Solution

  • The setw field width is defined for the next item to be output and is reset to 0 afterwards. This is why only the text is displayed on 25 chars and not the remaining output on the line.

    The right and left justifier define where the fill chars are to be put in the field. This means that it applies only to the current field if it has a defined width. This is why the justification is not applied to the items following the text.

    Here you to obtain the expected result:

    cout <<setw(25)<< left<< "Loan amount:" <<  "$ "<< setw(10)<<right << amount << endl;
    cout <<setw(25)<< left << "Monthly Interest Rate:"<<"  "<<setw(10)<<right<< rateMonthly << " %" << endl; 
    

    If you want the $ to be next to the number, you have to make sure that the $ and the number are concatenated into a single object to output, either by puting them together in a single string, or by using monetary format.