Connecting Tech Pros Worldwide Help | Site Map

Structures

Newbie
 
Join Date: Sep 2009
Posts: 8
#1: Oct 5 '09
I need to build a structured program that has to deal with pizza size, pounds of cheese, and price of the pizza in C++. I haven't got far because instead of the program actually having the defined variables the user has to put their own variables in.

struct pizza { //declare a structure
int size; //size of the pizza in inches
int cheeseAmount; //amount of cheese in pounds
float price; //price of the pizza
};



int main()
{
pizza pizza1; //define a structure variable
//give values to structre members
pizza1.size =
pizza1.cheeseAmount =
pizza1.price =


//display structure members
cout << " Enter the size of the pizza in inches: " << pizza1.size;

cout << " Enter the pounds of cheese to be added: " << pizza1.cheeseAmount;

cout << " Enter the price of the pizza: " << pizza1.price;

cout << " \n A " << pizza1.size << " inch pizza with " << pizza1.cheeseAmount << " pounds of cheese will cost\n " << pizza1.price ;


Is what I have so far I just need to know what I need to do to get it to work the the correct structure.
Moderator
 
Join Date: Mar 2007
Location: North Bend Washington USA
Posts: 5,366
#2: Oct 5 '09

re: Structures


Your use of the struct looks OK.

But assigning ot the struct members directly in main(), while it works, does violate the priciple of a structured program.

That is a structured program consists of a hierarchy of functions where the code of the lowest functions is obvious.

For your program to be structured, you would have to:

Expand|Select|Wrap|Line Numbers
  1. int main()
  2. {
  3.     Call a function to get the size of the pizza
  4.     Call a function to change the size of the pizza
  5.     Ditto for the other pizza members
  6.     etc...
  7.     Call a function to display the updated pizza
  8.  
  9. }
Typically, these functions would have a pointer to the pizza as one argument so that the correct pizza could be updated. There would be other arguments based on what is being done
Newbie
 
Join Date: Sep 2009
Posts: 8
#3: Oct 5 '09

re: Structures


I know but I am confused on how the function is set up. What do I put in all those fields?
Moderator
 
Join Date: Mar 2007
Location: North Bend Washington USA
Posts: 5,366
#4: Oct 5 '09

re: Structures


You don't need to worry about the fields in the struct.

You pass a pointer to a pizza variable:

Expand|Select|Wrap|Line Numbers
  1. void ChangeSize(pizza* ptr, int newsize)
  2. {
  3.      ptr->size = newsize
  4. }
The function should know what it's doing. This example fiddles with the size member and leaves all the other members alone. You write other functions that work with the other members and you guarantee that all the functions are called.

This way each function only has to worry about its job and not worry about the entire struct variable.
Reply


Similar C / C++ bytes