// ;-------------------------------------------------------------------- // ;Program Name: demoprob23.cpp // ;Problem Numb: 23 // ;Author: Jim Adams // ;Class: CIS162AB // ;Date: November 07,2001 // ;Description: Demonstrates a Money Class // ;--------------------------------------------------------------------- #include // For cout, etc #include // For sprintf #include // For isdigit() #include // For string function such as strcpy #include // For setw() struct string // for easier passing to and from functions { char st[20]; }; class Money { public: string dollar(int); // member function prototype string dollar(float); // member function prototype string dollar(long); // member function prototype string dollar(double); // member function prototype string expand(double); // member function for format }; Money m1; // Declare abstract variables string str; // Special structure for functions void main(void) { // Set up the test data, all four data types int d1=10; float d2=(float) 128.99; long d3=12345678; double d4=1234567890.12; // Call the format member function str=m1.dollar(d1); cout << str.st << endl; str=m1.dollar(d2); cout << str.st << endl; str=m1.dollar(d3); cout << str.st << endl; str=m1.dollar(d4); cout << str.st << endl; } string Money::dollar(int d) // Member Function { double pass; pass=d; return(m1.expand(pass)); } string Money::dollar(float d) // Member Function { double pass; pass=d; return(m1.expand(pass)); } string Money::dollar(long d) // Member Function { double pass; pass=d; return(m1.expand(pass)); } string Money::dollar(double d) // Member Function { double pass; pass=d; return(m1.expand(pass)); } // Member function to format the data // Passed: A double with the value to format // Returns: A 20-byte string with formatted dollar amount string Money::expand(double d) // Member Function { char st1[15]; // ASCII version of input number char st2[20]; // Converted and formatted number int k; int i; memset(st2,' ',20); sprintf(st1,"%14.2f",d); st2[19]=0; // string termination st2[18]=st1[13]; // move in hundreths st2[17]=st1[12]; // move in tenths st2[16]=st1[11]; // move in point k = 15; for (i=10; i>=0; i--) { if (isdigit(st1[i])) // test for 0-9 st2[k--]=st1[i]; else break; // otherwise bail if (i==8 || i==5 || i==2) st2[k--]=','; // shove in a comma } if (st2[k+1]==',') // place $-sign st2[k+1]='$'; else st2[k]='$'; strcpy(str.st,st2); // copy to string struct return(str); // return the formatted string }