This doesn't work?

When I build the following code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>

using namespace std;

int main()
{
        cout << fixed << showpoint << setprecision(2);
	outFile.open("EmployeeCard.txt");
	string empFName, empLName;
	double grossAmount;
	cout << "Please enter employee first name: ";
	cin >> empFName;
	cout << "Please enter employee last name: ";
	cin >> empLName;
	cout << "Please enter gross pay: ";
	cin >> grossAmount;
	outFile << empFName << " " << empLName << setfill('.') << endl;
	outFile << setw(26) << left << "Gross Amount: " << right << setw(9) << " $" << grossAmount << endl;
	outFile << setw(26) << left << "Federal Tax: " << right << setw(9) << " $" << grossAmount * .15 << endl;
	outFile << setw(26) << left << "State Tax: " << right << setw(9) << " $" << grossAmount * .035 << endl;
	outFile << setw(26) << left << "Social Security Tax: " << right << setw(9) << " $" << grossAmount * .0575 << endl;
	outFile << setw(26) << left << "Medicare/Medicaid Tax: " << right << setw(9) << " $" << grossAmount * .0275 << endl;
	outFile << setw(26) << left << "Pension Plan: " << right << setw(9) << " $" << grossAmount * .005 << endl;
	outFile << setw(26) << left << "Health Insurance: " << right << setw(9) << " $" << 75.00 << endl;
	outFile << setw(26) << left << "Net Pay: " << right << setw(9) << " $" << grossAmount - grossAmount * (.15 - .035 - .0575 - .0275 - .005) - 75 << endl;

return 0;
}

I get the following:

Awesome Possum
Gross Amount: ................... $10000.00
Federal Tax: .................... $1500.00
State Tax: ...................... $350.00
Social Security Tax: ............ $575.00
Medicare/Medicaid Tax: .......... $275.00
Pension Plan: ................... $50.00
Health Insurance: ............... $75.00
Net Pay: ........................ $9675.00
For some reason, the right side is not right-justified. I'd like to know why. Plese help. Thank you.
It is because the 'width' flag only applies to the next object you output (which is the dollar-sign). There is no direct way to prefix a dollar-sign to a number, but you can create a simple manipulator object to do it for you with its own overloaded stream insertion operator:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
struct dollar
  {
  double number;
  dollar( double number ): number( number ) { }
  };

ostream& operator << ( ostream& outs, const dollar& d )
  {
  ostringstream ss;
  ss.flags( outs.flags() );
  ss.precision( outs.precision() );
  ss << " $" << d.number;
  outs << ss.str();
  return outs;
  }


Now to display a specific quantity as a dollar amount, use it thus:

1
2
3
cout << fixed << showpoint << setprecision( 2 ) << setfill( '.' );
...
cout << setw(16) << right << dollar( 41.99 ) << endl;

Produces
......... $41.99


Hope this helps.
Topic archived. No new replies allowed.