element14 Community
element14 Community
    Register Log In
  • Site
  • Search
  • Log In Register
  • Community Hub
    Community Hub
    • What's New on element14
    • Feedback and Support
    • Benefits of Membership
    • Personal Blogs
    • Members Area
    • Achievement Levels
  • Learn
    Learn
    • Ask an Expert
    • eBooks
    • element14 presents
    • Learning Center
    • Tech Spotlight
    • STEM Academy
    • Webinars, Training and Events
    • Learning Groups
  • Technologies
    Technologies
    • 3D Printing
    • FPGA
    • Industrial Automation
    • Internet of Things
    • Power & Energy
    • Sensors
    • Technology Groups
  • Challenges & Projects
    Challenges & Projects
    • Design Challenges
    • element14 presents Projects
    • Project14
    • Arduino Projects
    • Raspberry Pi Projects
    • Project Groups
  • Products
    Products
    • Arduino
    • Avnet Boards Community
    • Dev Tools
    • Manufacturers
    • Multicomp Pro
    • Product Groups
    • Raspberry Pi
    • RoadTests & Reviews
  • Store
    Store
    • Visit Your Store
    • Choose another store...
      • Europe
      •  Austria (German)
      •  Belgium (Dutch, French)
      •  Bulgaria (Bulgarian)
      •  Czech Republic (Czech)
      •  Denmark (Danish)
      •  Estonia (Estonian)
      •  Finland (Finnish)
      •  France (French)
      •  Germany (German)
      •  Hungary (Hungarian)
      •  Ireland
      •  Israel
      •  Italy (Italian)
      •  Latvia (Latvian)
      •  
      •  Lithuania (Lithuanian)
      •  Netherlands (Dutch)
      •  Norway (Norwegian)
      •  Poland (Polish)
      •  Portugal (Portuguese)
      •  Romania (Romanian)
      •  Russia (Russian)
      •  Slovakia (Slovak)
      •  Slovenia (Slovenian)
      •  Spain (Spanish)
      •  Sweden (Swedish)
      •  Switzerland(German, French)
      •  Turkey (Turkish)
      •  United Kingdom
      • Asia Pacific
      •  Australia
      •  China
      •  Hong Kong
      •  India
      •  Korea (Korean)
      •  Malaysia
      •  New Zealand
      •  Philippines
      •  Singapore
      •  Taiwan
      •  Thailand (Thai)
      • Americas
      •  Brazil (Portuguese)
      •  Canada
      •  Mexico (Spanish)
      •  United States
      Can't find the country/region you're looking for? Visit our export site or find a local distributor.
  • Translate
  • Profile
  • Settings
Code Exchange
  • Technologies
  • More
Code Exchange
Blog C++ Tutorial - Structures
  • Blog
  • Forum
  • Documents
  • Events
  • Polls
  • Files
  • Members
  • Mentions
  • Sub-Groups
  • Tags
  • More
  • Cancel
  • New
Join Code Exchange to participate - click to join for free!
  • Share
  • More
  • Cancel
Group Actions
  • Group RSS
  • More
  • Cancel
Engagement
  • Author Author: oneleggedredcow
  • Date Created: 27 Feb 2013 2:24 AM Date Created
  • Views 2346 views
  • Likes 1 like
  • Comments 6 comments
  • code_exchange
  • Code Exchange
  • raspberry_pi
  • code
  • rpi
  • learnc++
Related
Recommended

C++ Tutorial - Structures

oneleggedredcow
oneleggedredcow
27 Feb 2013

Introduction

In the previous tutorial, we talked about arrays, which allow you to store many related values of the same data type.  In this tutorial, we are going to talk about structures, which allow you to store related values of different data types.

Code

So, let’s jump in with an example:

 

struct Inventory

{

double Money;

 

int GrapesCount;

int BlueberriesCount;

int StrawberriesCount;

int RaspberriesCount;

};


This code defines a structure (struct) called Inventory, which stores 5 pieces of information: current amount of money, current number of grapes, blueberries, strawberries, and raspberries.  Notice that they all aren’t the same data type, and that we could give descriptive names to everything that we are storing within it.  This is unlike the array, which just had an index, which described the values location in the array.

 

Now, you might be looking at the struct and thinking to yourself, that’s a weird group of things to put together, where are we going with this?  We are going to be creating a small game in the style of the old calculator game drug wars, but instead of drugs, we are going to be buying and selling fruit.  So, this struct is going to store the current player’s state.

 

So, the idea of the game is that you go from fruit stand to fruit stand, buying and selling fruit until you have acquired a certain goal, in this case 5 raspberries.  So, to start out we need to create a struct to store the user’s items and it looks something like this:

 

Inventory mine;

mine.Money = 50.00;

mine.GrapesCount = 20;

mine.BlueberriesCount = 5;

mine.StrawberriesCount = 0;

mine.RaspberriesCount = 0;


Now, in the latest C++ standard, a new simpler way to create a struct was introduced:

 

Inventory test = { 50.00, 20, 5, 0, 0 };


The two code statements produce the same result.  So, now that we have a struct to store the user’s inventory, we can create a struct to store the fruit stands prices:

 

struct PriceList

{

double GrapesPrice;

double BlueberriesPrice;

double StrawberriesPrice;

double RaspberriesPrice;

};


Notice that the items in a struct do not have to be different data types, they can all be of the same type, like the PriceList.  So, why not use an array?  An array would work, but it wouldn’t be very descriptive as to what each element was. If it was an array, you would have to remember that the 3rd item in the array was the price of strawberries.  However, with a struct, the name helps remind you what it stands for.

 

Now we can write two functions to print out the contents of our struct:

 

void print(Inventory inventory)

{

cout << "Inventory:" << endl;

cout << "\t$" << inventory.Money << endl;

cout << "\tGrapes:       " << inventory.GrapesCount << endl;

cout << "\tBlueberries:  " << inventory.BlueberriesCount << endl;

cout << "\tStrawberries: " << inventory.StrawberriesCount << endl;

cout << "\tRaspberries:  " << inventory.RaspberriesCount << endl;

}


void print(PriceList prices)

{

cout << "Prices:" << endl;

cout << "\tGrapes:       $" << prices.GrapesPrice << endl;

cout << "\tBlueberries:  $" << prices.BlueberriesPrice << endl;

cout << "\tStrawberries: $" << prices.StrawberriesPrice << endl;

cout << "\tRaspberries:  $" << prices.RaspberriesPrice << endl;

}


Now there is a trick going on here that we haven’t talked about yet.  Notice that I have two functions with the same name, but they take in different data types as input.  The c++ compiler is smart enough to know that if we have an Inventory struct that we want the first one, and if we have a PriceList struct that we want the second one.  The technical term for this is function overloading.

 

As far as the new code goes, that’s about it.  All that is left is randomly generating prices for the various fruits and handling whether the user wants to sell or buy fruit before moving on to the next fruit stand.  If the user chooses by, we need to check whether or not they have enough money and if the user chooses sell, we need to make sure that they have enough fruit to sell.

 

The full code for the game is attached below.

Summary

In this tutorial, we demonstrated the use of structures to store related values of different data types. We then created a small game that uses structures to store information about the user’s current state.

 

In the next tutorial, we will introduce classes, which are a way to store related information (of different data types) and functions that operate on that data.

 

If you have any questions or comments about what was covered here, post them to the comments.  I watch them closely and will respond and try to help you out.

Tutorial Index

01 - Hello Raspberry Pi

02 - Reading User Input

03 - If Statement

04 - For Loops

05 - While Loops

06 - Functions

07 - Data Types

08 - Arrays

09 - Structures

10 - Classes

11 - Pointers

12 - Dynamic Arrays

13 - Linked List

14 - Linked List Operations

15 - STL List/Vector

16 - Templates

17 - Inheritance

18 - File I/O

19 - Strings

20 - Constants

21 - Hash Tables

Attachments:
09_FruitWars.zip
  • Sign in to reply
  • oneleggedredcow
    oneleggedredcow over 10 years ago in reply to oneleggedredcow

    Should be fixed now, thanks for the heads up!

    • Cancel
    • Vote Up 0 Vote Down
    • Sign in to reply
    • More
    • Cancel
  • oneleggedredcow
    oneleggedredcow over 10 years ago in reply to Former Member

    Opps, I'll fix that tonight.

    • Cancel
    • Vote Up 0 Vote Down
    • Sign in to reply
    • More
    • Cancel
  • Former Member
    Former Member over 10 years ago

    Well, I found the problem with the code here, which had a problem both with GCC on Raspbian and on Visual Studio 2013 on Windows 7. The problem is: _TCHAR* is not declared. The solution is to replace:

     

    int _tmain(int argc, _TCHAR* argv[])
      {
       cout.setf(ios::fixed, ios::floatfield);
       cout.precision(2);

     

    with:

     

    int main()

    {

    • Cancel
    • Vote Up 0 Vote Down
    • Sign in to reply
    • More
    • Cancel
  • Former Member
    Former Member over 10 years ago

    09_FruitWars.cpp does not compile. Fix please.

    • Cancel
    • Vote Up 0 Vote Down
    • Sign in to reply
    • More
    • Cancel
  • oneleggedredcow
    oneleggedredcow over 12 years ago in reply to shabaz

    You are totally correct, it is a good idea to typdef your structs because of potential naming conflicts.  Here's a link that explains in more detail what is going on:

     

    http://stackoverflow.com/questions/612328/difference-between-struct-and-typedef-struct-in-c

     

    Thanks for the comment and clarifying that!

    • Cancel
    • Vote Up 0 Vote Down
    • Sign in to reply
    • More
    • Cancel
>
element14 Community

element14 is the first online community specifically for engineers. Connect with your peers and get expert answers to your questions.

  • Members
  • Learn
  • Technologies
  • Challenges & Projects
  • Products
  • Store
  • About Us
  • Feedback & Support
  • FAQs
  • Terms of Use
  • Privacy Policy
  • Legal and Copyright Notices
  • Sitemap
  • Cookies

An Avnet Company © 2025 Premier Farnell Limited. All Rights Reserved.

Premier Farnell Ltd, registered in England and Wales (no 00876412), registered office: Farnell House, Forge Lane, Leeds LS12 2NE.

ICP 备案号 10220084.

Follow element14

  • X
  • Facebook
  • linkedin
  • YouTube