In the following code, at the end, I would like to have "Total Weekly Calories: " displayed along with the total amount.
However I have "Total Weekly Calories:" display seven times and the correct total is in the seventh spot. How can I get "Total...to show only once and the correct amount to display? I have tried everything that I can think of and still can not come up with anything. I can get the "Total Weekly Calories" to display once but then the amount of calories is incorrect. Please see if you can see my errors?
Code:
#include<iostream.h>
#include<conio.h>
#include<string.h>
class Meal
{
friend ostream& operator<<(ostream &out, const Meal &aMeal);
friend istream& operator>>(istream &in, Meal &aMeal);
private:
char entree[20];
int calorie;
public:
Meal(char ent[] = "Pizza", int cal = 0);
Meal operator+(Meal &aMeal);
Meal( const Meal& toCopy)
{
copy(toCopy);
}
const Meal& operator=(const Meal& rhs){
copy(rhs);
return *this;
}
void displayMeal();
protected:
void copy( const Meal& rhs){
// do not copy entree
calorie = rhs.calorie;
}
};
Meal::Meal(char ent[], int cal )
{
strcpy(entree,ent);
calorie = cal;
};
Meal Meal::operator+(Meal &aMeal)
{
Meal exam;
exam.calorie = calorie + aMeal.calorie;
return(exam);
};
void Meal::displayMeal()
{
cout<<"Total weekly calories: "<<calorie<<endl;
};
ostream& operator<<(ostream &out, const Meal &aMeal)
{
out<<"Total weekly calories: "<<aMeal.calorie<<endl;
return(out);
};
istream& operator>>(istream &in, Meal &aMeal)
{
cout<<endl; //clears
cout<<"Enter the entree name: ";
in>>aMeal.entree;
cout<<"Enter the amount of calories: ";
in>>aMeal.calorie;
return(in);
};
void main()
{
Meal meals[7];
Meal temp;
for (int i = 0; i < 7; i++)
cin>>meals[i];
for (i = 0; i < 7; ++i)
{
temp = temp + meals[i];
temp.displayMeal();
}
getch();
};