Here's an idea for you (because, as you said, you shouldn't use globals unless absolutely necessary, and in your case, it's not necessary):
1.Create a class ingredient
:
class ingredient {
public:
string name;
string unit;
double quantity;
ingredient(string n, string u, double q) :
name(n), unit(u), quantity(q) { }
}
2.Create a class recipe
:
class recipe {
vector<ingredient> the_recipe;
public:
recipe() : the_recipe() {}
void addIngredient(const ingredient& i) {
the_recipe.push_back(i);
}
void printProportions(const int servings) {
printf("For %d servings, you need", servings);
for(int i = 0; i < the_recipe.size(); ++i) {
printf("%f %s of %s\n", the_recipe[i].quantity * servings, the_recipe[i].unit, the_recipe[i].name);
}
}
};
What do you think?
UPDATE
3.Use it in your program:
Here's an example of how you can use it (also note I've modified my struct
above. In order to avoid possible confusion, I changed it to a class. They're both the same essentially in C++, with one minor difference). Anyway, here's an example:
int main() {
// create the ingredient objects
ingredient macaroni("macaroni", "grams", 50), cheese("cheese", "grams", 20);
// create a plain recipe
recipe mac_n_cheese;
// add the ingredients
mac_n_cheese.addIngredient(macaroni);
mac_n_cheese.addIngredient(cheese);
// then finally print the proportions using printProportions
mac_n_cheese.printProportions(2); // for 2 people
return 0;
}