Can someone please help me with this? I have been struggling with this for days now, and for some reason, my instructor's help is not working for me. I am not sure if it is because he is from Germany and I am taking courses on-line, or if it is because I am totally confused - or a combination of both. I am supposed to end up being able to do the following: Ask the user how many prices he/she wants to enter, then read each price one by one, then compute the sum of all prices times 3 and their average, and then print two amounts. This is my first program using classes. I apologize if this is located somewhere on the forums; I didn't see it and I really did look. This is also my very first post, so I apologize if I didn't do it exactly right.

``````#include <iostream>
using namespace std;

class TMoney  {

public:

TMoney() {int dollars=0; int cents=0; int amount=0;};
int int_get_dollars() {return amount/100;};
int int_get_cents() {return amount % 100;};
void set(int dollars, int cents);
void Print();
bool greater(TMoney b) {return (b.amount>amount);};
bool equals (TMoney b) {return (b.amount==amount);};
void add(TMoney b) {amount += b.amount;};
void times (int i){amount*=i;};
void divide_by (int i){amount/=i;};

private:
int dollars;
int cents;
int amount;
};

void TMoney::set(int dollars, int cents){
if (dollars<0)
amount=-1*(dollars*100 + cents);
else
amount=dollars*100+cents;
}

void TMoney::Print(){
if (dollars<=0) {
cout<<"-\$"<<dollars<<"."<<cents<<endl;
}
else if (dollars>0){
cout<<"\$"<<dollars<<"."<<cents<<endl;
}
}

char sign, dec;
int dollars, cents;

cin>>sign>>dollars>>dec>>cents;

set(dollars, cents);
}

void main(void){

TMoney t;
int i, N;
cout<<"How many prices would you like to enter?";
cin>>N;
for (i=0;i<N;i++){
}
}``````
Ancient Dragon commented: thanks for attempting to use code tags +20

## All 9 Replies

Did your instructor give you some requiements what TMoney is supposed to look like? Or are you free to write it any way you want ? Personally I think your class contains way too many methods to do only the few things you posted, and the only data object you need is `float money;` . Given that, Print() can be reduced to this because cout will display the negative sign if needed and the decimal point.

``````void TMoney::Print(){
cout << precision(2) << width(4) <<  money << "\n";
}``````

AD - no disrespect, but I don't want you programming for my bank! 8-)

float is not a good choice for dealing with money amounts - the problems of (lack of) precision show up very easily. Even using doubles can lose pennies quickly the more you manipulate the numbers.

That said, there's a place for floating point types in this class. For instance, the read( ) method would be more reliable reading into a double, then converting to the integer dollar and cents amounts.

``````void TMoney::Read(){
char sign, dec;
int dollars, cents;

cin>>sign>>dollars>>dec>>cents;

set(dollars, cents);
}``````

This depends on the user exactly, and always, entering a sign, 0 or more dollars, a decimal, and the cents. We all know users are not that well trained.
A more reliable (but not guaranteed foolproof) method might be:

``````void TMoney::Read(){
double input;
int dollars, cents;
cin >> input;

dollars = (int) input;
cents = input - dollars;
//or use the modf( ) function if you feel more daring

set(dollars, cents);
}``````

Now the problem for toneeg is how to do the arithmetic. With the integer parts, deal dollars to dollars, cents to cents, and find out how many extra dollars' worth you have in the cents values.
Consider adding 4.65 and 3.80. 4 + 4 = 7. 65 + 80 = 145. That's greater than or equal to 100, so strip out the 100 cents and add that to the result dollars. Thus 8.45 is the result. Multiply and divide are just a bit more complex. Start with the easy one.

Hi Ancient Dragon,

don't shoot me, but yes, my instructor did give me specific instructions on how the TMoney class is supposed to look. The whole assignment is listed below.

Exercises
1. TMoney assignment: Create class TMoney that contains information about an amount of dollars and cents. This class should have:
o Constructors TMoney() that assigns the amount of money of 0 dollars and 0 cents.
o Methods:
 int get_dollars()
returns the amount of dollars stored in a TMoney object.
 int get_cents()
returns the amount of cents stored in a TMoney object.
 void set(int dollars, int cents)
sets the new amount.
 void print()
prints the stored amount to the standard output (cout) in the format: \$xxx.xx or -\$xxx.xx.
reads an amount of money from the standard input (cin) and stores in the object. The input format should be \$xxxx.xx or -\$xxx.xx.
Hint: write a function similar to the function readDouble discussed earlier.
 bool greater(TMoney b)
takes another instance of TMoney object as a parameter and compares with the amount stored in the object invoking the method, returns true if the stored amount is greater than the amount in the parameter, false otherwise.
 bool equals(TMoney b)
takes another instance of TMoney object as a parameter and compares with the amount stored in the object invoking the method, returns true if the stored amount is equal to the amount in the parameter, false otherwise.
takes another instance of TMoney object as a parameter and adds two amounts together. The new amount should be stored in the object invoking the method.
 void times(int i)
multiplies the stored amount of money by i. For example, if the object change of the TMoney class currently has \$1.20, then after using change.times(5) it should contain exactly \$6.00
 void divide_by(int i)
divides the stored amount of money by i. For example, if the object change of the TMoney class currently has \$1.20, then after using change.divide_by(5) it should contain exactly \$0.24
o TMoney object may store both positive and negative amounts;
o programmers who use this class should not have a direct access to the data stored in the class only through the class methods;
o you are free to choose any way you like to store information inside the class. You may keep it as two integers, one integer, a double, etc, but all functions suppose to take and return exactly the described values (integers).
Hint: we would suggest storing the whole amount as an amount of cents. In this case you will keep \$1.20 as 120 and you will use division by 100 (amount/100) to get the number of dollars and module operator % (amount % 100) to retrieve amount of cents.
2. Create a program to test your new TMoney class. This program should read a number of different prices from the user and compute their sum and their average. As the result it should print the sum multiplied by 3 and the average. Please use the methods you have created for the TMoney class. More exactly, this program should do the following:
1. prompt the user for the number of prices user wants to enter
2. read all prices one by one
3. compute the sum of all prices times 3 and compute their average
4. print two amounts.

Did your instructor give you some requiements what TMoney is supposed to look like? Or are you free to write it any way you want ? Personally I think your class contains way too many methods to do only the few things you posted, and the only data object you need is `float money;` . Given that, Print() can be reduced to this because cout will display the negative sign if needed and the decimal point.

``````void TMoney::Print(){
cout << precision(2) << width(4) <<  money << "\n";
}``````

Hi vmanes,

I actually had tried to set up my Read() function similar to what you have, and I am going to set it up that way again. My biggest problem is confusion about how to use the amount to go with all of the methods that I have set up. I don't know how to make the connection. If I read an amount, and then I use set() inside the Read() function, how do I then take the amount(s) that the user has entered and manipulate that information to get the sum of all the prices which would allow me to multiply that sum by three, and then print out the amounts? It doesn't seem like I can just use t.add(), or t.times() just like that. How will the methods know what to work on? Also, am I looping correctly?

I am thinking that maybe I am missing something really simple, but this is driving me crazy to the point of having second thoughts about my field of study. Confidence is low.

AD - no disrespect, but I don't want you programming for my bank! 8-)

float is not a good choice for dealing with money amounts - the problems of (lack of) precision show up very easily. Even using doubles can lose pennies quickly the more you manipulate the numbers.

That said, there's a place for floating point types in this class. For instance, the read( ) method would be more reliable reading into a double, then converting to the integer dollar and cents amounts.

``````void TMoney::Read(){
char sign, dec;
int dollars, cents;

cin>>sign>>dollars>>dec>>cents;

set(dollars, cents);
}``````

This depends on the user exactly, and always, entering a sign, 0 or more dollars, a decimal, and the cents. We all know users are not that well trained.
A more reliable (but not guaranteed foolproof) method might be:

``````void TMoney::Read(){
double input;
int dollars, cents;
cin >> input;

dollars = (int) input;
cents = input - dollars;
//or use the modf( ) function if you feel more daring

set(dollars, cents);
}``````

Now the problem for toneeg is how to do the arithmetic. With the integer parts, deal dollars to dollars, cents to cents, and find out how many extra dollars' worth you have in the cents values.
Consider adding 4.65 and 3.80. 4 + 4 = 7. 65 + 80 = 145. That's greater than or equal to 100, so strip out the 100 cents and add that to the result dollars. Thus 8.45 is the result. Multiply and divide are just a bit more complex. Start with the easy one.

>>AD - no disrespect, but I don't want you programming for my bank!
Shucks! And I was going to funnel those extra pennies into my own bank account :)

But your solution has the same problem as mine -- upgrading from float to double does not affect that possible imprecision.

why don't you use this hint that your instructor has given you? it seems to be the simplest way to implement TMoney:
> Hint: we would suggest storing the whole amount as an amount of cents. In this case you will
> keep \$1.20 as 120 and you will use division by 100 (amount/100) to get the number of dollars
> and modulo operator % (amount % 100) to retrieve amount of cents.
and avoid floating point altogether; for calculations, for input, for everything.

> It doesn't seem like I can just use t.add(), or t.times() just like that. How will the methods know what to work on?
the method TMoney::add should take an argument (amount to be added), multiply should also take an argument (the multiplier). so your code would look like t = t.add(t1), or t = t.times(3) etc. these are there in the code you posted originally. a const correct version of which would be

``````{
// ...
bool greater( TMoney b) const ;
bool equals (TMoney b)  const ;
TMoney times (int i) const ;
// etc.
};``````

Hi vijayan121,

in a perfect world, my brain would kick into gear and I would actually get how to do that. This is where I am stuck. My mind is not grasping the whole concept of how to read the amount, and use that same amount to go with the other methods that I have in the class. I hope you or somebody can understand what I mean. The instructor gave another hint to use a funtion similar to a readMoney() function we had written before. Here is the language I used for this function before. I don't understand how to use it with the class. It seems like the whole idea of classes is really messing with my head and all that I thought I knew about C++. I really am trying, sometimes I think too hard. I am not sure I understand class methods well enough, and I think this is why I am not getting it.

``````double readMoney(void)	//re-delcaration of the readMoney function for use with this program
{
char   amount;
double result = 0;
double factor = 10;

cin.get(amount); // read the very first symbol from the user

if( amount=='\$'){

cin.get(amount);

} 	// check if the first symbol is a dollar sign if it is read the next character

else	{
cout<<"Error, please enter a dollar amount, starting with a \$ sign!\n";
exit (1);
}		//if not, print error message asking for correct starting input

while( isdigit(amount) || (amount=='.' && factor>0.1) ){	//loop to repeat if character is correct
if( isdigit(amount) ){
if( factor > 0.1 ){

result = factor * result + (amount - '0');  //before reading the decimal point
}

else{

result += (amount - '0') * factor;	//after reading decimal point
factor /= 10;
}
}
else{
factor = 0.1;		// we just read the decimal point
}
cin.get(amount); 		// read the next symbol
}

return result;
}

int main(void)
{

double num, dollars, cents;
int i = 0;
for (i=0;i<5;i++){	//looping to get five entries from the user
cout<<"Please enter a dollar amount, including dollars and cents:\n";
num = readMoney();  // getting input from the user via the function created
dollars = static_cast<int>(num);
cents = static_cast<int>((num-dollars)*100);
cout<<"You entered " <<dollars<<" dollars and "<<cents<<" cents.\n";

}

}``````

why don't you use this hint that your instructor has given you? it seems to be the simplest way to implement TMoney:
> Hint: we would suggest storing the whole amount as an amount of cents. In this case you will
> keep \$1.20 as 120 and you will use division by 100 (amount/100) to get the number of dollars
> and modulo operator % (amount % 100) to retrieve amount of cents.
and avoid floating point altogether; for calculations, for input, for everything.

> It doesn't seem like I can just use t.add(), or t.times() just like that. How will the methods know what to work on?
the method TMoney::add should take an argument (amount to be added), multiply should also take an argument (the multiplier). so your code would look like t = t.add(t1), or t = t.times(3) etc. these are there in the code you posted originally. a const correct version of which would be

``````{
// ...
bool greater( TMoney b) const ;
bool equals (TMoney b)  const ;
TMoney times (int i) const ;
// etc.
};``````

ok, here is a (somewhat similiar) example.

``````#include <iostream>

class time_of_day // hh:mm:ss
{
public :
time_of_day( int hr, int min, int sec ) ;
bool equals( time_of_day that ) const ;
time_of_day advance_by_secs( int secs ) const ;
int hour() const { return seconds_since_midnight / (60*60) ; }
// etc
private: int seconds_since_midnight ;
};

time_of_day::time_of_day( int hr, int min, int sec )
{
// validate hr(0-23), min(0-59), sec(0-59)
seconds_since_midnight = hr * 60 * 60 + min * 60 + sec ;
}

bool time_of_day::equals( time_of_day that ) const
{
// called as: time_of_day_one.equals( time_of_day_two )
// equals is a binary operation; compares two
// time_of_day variables for equivalence.
// one of them is the time_of_day on which the function
// is called (time_of_day_one); identified by the this pointer
// the other (time_of_day_two) is available as the arg 'that'
return /* this-> */ seconds_since_midnight ==
that.seconds_since_midnight ;
}

time_of_day time_of_day::advance_by_secs( int secs ) const
{
enum { SECS_PER_DAY = 24*60*60 };
time_of_day result = *this ; // make a copy
result.seconds_since_midnight += secs ;

// this is just to correct for overflow or underflow
// could ignore this for now and focus on the rest.
while( result.seconds_since_midnight < 0 )
result.seconds_since_midnight += SECS_PER_DAY ;
if( result.seconds_since_midnight >= SECS_PER_DAY )
result.seconds_since_midnight %= SECS_PER_DAY ;
return result ;
}

int main()
{
int hr = 10, min=32, sec=45 ;
time_of_day tod_one( hr, min, sec ) ;
// now tod_one's member variable seconds_since_midnight
// has safely stored the value computed from 10:32:45

// and tod_two's member variable seconds_since_midnight
// has safely stored it's value

std::cout << "equal? " << std::boolalpha
<< tod_one.equals( tod_two ) << '\n' ;
}``````

if you still are confused:
a. give it a rest for now. have a good night's sleep and then come back to it.
b. look up in your text book: member functions, this pointer etc.
c. try writing the program
i'm certain that you can do this quite easily with a clear head.

vijayan121,

first, let me thank you for making such a great effort to help me. I am still confused, but I know that moment when it all clicks together is not far off. Some things that you mention in your example I have not even gotten to in the lectures given by my instructor. For example, like *this, and pointers within classes...this is all foreign to me. I am three assignments behind now, and it is only because I can't just move on. The next assignments build on this one, and I am stuck on stupid. My instructor is great, but he has a tendency to explain things to me like I have been a programmer prior to now. If I could just get the basics of classes together so that I have a solid understanding I believe I could get past this. I am sure I will get it, but I need to get it like yesterday. I have been reading today at www.functionx.com - just in case anyone else needs help, I find that the informaton listed in the tutorials there is very detailed. I think I have been looking at this for too long, but at the same time, I am one of those kind of people who have a hard time moving on to the next thing - anything - if I can't figure something out. If I try to stay away, my laptop keeps calling me. It is hard to believe I am so addicted to something that drives me so crazy. I almost feel like giving up on programming but I really love it; it just has a way of making me wonder if I am as intelligent as I thought I was. I think I need a margarita. :)

ok, here is a (somewhat similiar) example.

``````#include <iostream>

class time_of_day // hh:mm:ss
{
public :
time_of_day( int hr, int min, int sec ) ;
bool equals( time_of_day that ) const ;
time_of_day advance_by_secs( int secs ) ;
int hour() const { return seconds_since_midnight / (60*60) ; }
// etc
private: int seconds_since_midnight ;
};

time_of_day::time_of_day( int hr, int min, int sec )
{
// validate hr(0-23), min(0-59), sec(0-59)
seconds_since_midnight = hr * 60 * 60 + min * 60 + sec ;
}

bool time_of_day::equals( time_of_day that ) const
{
// called as: time_of_day_one.equals( time_of_day_two )
// equals is a binary operation; compares two
// time_of_day variables for equivalence.
// one of them is the time_of_day on which the function
// is called (time_of_day_one); identified by the this pointer
// the other (time_of_day_two) is available as the arg 'that'
return /* this-> */ seconds_since_midnight ==
that.seconds_since_midnight ;
}

{
enum { SECS_PER_DAY = 24*60*60 };
time_of_day result = *this ; // make a copy
/* this-> */ result.seconds_since_midnight += secs ;

// this is just to correct for overflow or underflow
// could ignore this for now and focus on the rest.
while( result.seconds_since_midnight < 0 )
result.seconds_since_midnight += SECS_PER_DAY ;
if( result.seconds_since_midnight >= SECS_PER_DAY )
result.seconds_since_midnight %= SECS_PER_DAY ;
return result ;
}

int main()
{
int hr = 10, min=32, sec=45 ;
time_of_day tod_one( hr, min, sec ) ;
// now tod_one's member variable seconds_since_midnight
// has safely stored the value computed from 10:32:45

// and tod_two's member variable seconds_since_midnight
// has safely stored it's value

std::cout << "equal? " << std::boolalpha
<< tod_one.equals( tod_two ) << '\n' ;