//Implementation for the class Money defined in Display 9.14. #include #include #include #include #include "money.h" const int FALSE = 0; const int TRUE = 1; //If your implementation does not include labs, then removed the //comments delimiters around the following prototype and around the //corresponding function definition, which is at the end of this file. /* long labs(long number); //returns the absolute value of number. */ //Prototype for use in the definition of the overloaded input operator >>: int digit_to_int(char c); //Precondition: c is one of the digits '0' through '9'. //Returns the integer for the digit; e.g., digit_to_int('3') returns 3. //Uses iostream.h, ctype.h, stdlib.h, and constants TRUE and FALSE: istream& operator >>(istream& ins, Money& amount) { char one_char, decimal_point, digit1, digit2; //digits for the amount of cents long dollars; int cents, negative;//set to TRUE if input is negative. ins >> one_char; if (one_char == '-') { negative = TRUE; ins >> one_char; //read '$' } else negative = FALSE; //if input is legal, then one_char == '$' ins >> dollars >> decimal_point >> digit1 >> digit2; if ( one_char != '$' || decimal_point != '.' || !isdigit(digit1) || !isdigit(digit2) ) { cout << "Error illegal form for money input\n"; exit(1); } cents = digit_to_int(digit1)*10 + digit_to_int(digit2); amount.all_cents = dollars*100 + cents; if (negative) amount.all_cents = -amount.all_cents; return ins; } int digit_to_int(char c) { return ( int(c) - int('0') ); } //Uses stdlib.h and iostream.h: ostream& operator <<(ostream& outs, const Money& amount) { long positive_cents, dollars, cents; positive_cents = labs(amount.all_cents); dollars = positive_cents/100; cents = positive_cents%100; if (amount.all_cents < 0) outs << "-$" << dollars << '.'; else outs << "$" << dollars << '.'; if (cents < 10) outs << '0'; outs << cents; return outs; } Money operator -(const Money& amount1, const Money& amount2) { Money temp; temp.all_cents = amount1.all_cents - amount2.all_cents; return temp; } Money operator -(const Money& amount) { Money temp; temp.all_cents = -amount.all_cents; return temp; } Money operator +(const Money& amount1, const Money& amount2) { Money temp; temp.all_cents = amount1.all_cents + amount2.all_cents; return temp; } int operator ==(const Money& amount1, const Money& amount2) { return (amount1.all_cents == amount2.all_cents); } int operator <(const Money& amount1, const Money& amount2) { return (amount1.all_cents < amount2.all_cents); } Money::Money(long dollars, int cents) { all_cents = dollars*100 + cents; } Money::Money(long dollars) { all_cents = dollars*100; } Money::Money( ) { all_cents = 0; } double Money::get_value( ) const { return (all_cents * 0.01); } /* long labs(long number) { if (number < 0) return (-number); else return number; } */