C++ Primer Plus Chapter 4 Exercise 5

c plus plusExercise five requires us to make a basic struct. Structs are useful for when you want to hold relevant information about an object. With structs we are getting closer to OOP programming.  Here is my solution to the problem:

5. The CandyBar structure contains three members. The first member holds the brand
name of a candy bar. The second member holds the weight (which may have a fractional
part) of the candy bar, and the third member holds the number of calories (an integer
value) in the candy bar. Write a program that declares such a structure and creates a
CandyBar variable called snack, initializing its members to “Mocha Munch”, 2.3, and
350, respectively. The initialization should be part of the declaration for snack. Finally,
the program should display the contents of the snack variable.

#include <iostream>
#include <string>

using namespace std;

struct candyBar
{
string brand;
float weight;
int calories;
};

int main()
{
candyBar snack = {"Mocha Munch", 2.3, 350};
cout << "The snack variable holds: \n";
cout << snack.brand << "\n";
cout << snack.weight << " ounces \n";
cout << snack.calories << " calories \n";

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