c++setw

C++ aligning characters to display neatly with any input implemented


I am having trouble keeping the ":" and the "$" aligned with whichever input the user implements through the cin command which is "numTShirts". It stays aligned if implemented 10 and under but discount goes out of place with any other input.

![implemented with 10] http://prntscr.com/gzms3m

![implemented with other] http://prntscr.com/gzmsjx

    cout << "\n" << endl;
        cout << fixed;
        cout << "Thank you for your purchase.\n" << endl;
        cout << "You bought " << numTShirts << " T-shirts\n" << endl;

        cout << "Subtotal Total" << setw(5) << ": $ " << right << setprecision(2) << subTotal << "\n" << endl;
        cout << setprecision(0) << "Discount(" << discountPCT << "%)" << setw(7) << ": $ " << right << showpoint << setprecision(2) << discount << "\n" << endl;
        cout << setfill('-') << setw(35) << "-\n" << endl;
        cout << setfill(' ');
        cout << "Total" << setw(14) << ": $ " << right << showpoint << setprecision(2) << totalPrice << endl;

enter image description here enter image description here


Solution

  • This is happening because the amount of discount is variable and according to it the space increases.

    As you show in the example when the discount is of one digit the aligning is the desired one, otherwise it is different.

    As the discoutn can be maximum of three digits (100%) then I'd suggest you two make three formatting of the output.

    one for 1 digit discount, 2 digit and 3 digit. by using a conditional statement you can show the respective in the output.