C++ Primer Plus Chapter 4 Exercise 8

c plus plus

Exercise 8 took a little finagling to make it ask for diameter first while outputting it second in order as the last program, without skipping over the name input. If you use some other methods for pointing to structs at the diameter input, you will see what I mean. I provided a few different methods of pointing to structs in this exercise. The “new” keyword was used as per directions to allocate memory for our structure. Alas, here is my solution:

Do Programming Exercise 7, but use new to allocate a structure instead of declaring a
structure variable. Also, have the program request the pizza diameter before it requests
the pizza company name.

#include <iostream>
#include <string>

using namespace std;

// pizza struct
struct pizza
{
string pizzaCompanyName;
int pizzaDiameter;
int pizzaWeight;
};

int main()
{

// "New" keyword used to allocate memory for the structure
pizza * pie = new pizza;

// Gather info
cout << "Enter the diameter of the pizza in inches: ";
(cin >> pie->pizzaDiameter).get(); // manipulate cin
cout << "Enter the name of the Pizza Company: ";
getline(cin, pie->pizzaCompanyName);
cout << "Enter the weight of the pizza in ounces: ";
cin >> (*pie).pizzaWeight; // Another method of pointing to a structure
cout << "\n";

// Output info
cout << "The pizza company name is: " << pie->pizzaCompanyName << endl;
cout << "The Diameter inches is: " << pie->pizzaDiameter << endl;
cout << "The weight in ounces is: " << pie->pizzaWeight << endl;

// Free memory used by our structure, important.
delete pie;

cin.get();
return 0;
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s