< Previous | Contents | Next >

Introducing the Hero’s Inventory

Program

The Heros Inventory program maintains the inventory of a hero from a typical RPG. Like in most RPGs, the hero is from a small, insignificant village, and his father was killed by an evil warlord. (Whats a quest without a dead father?) Now that the hero has come of age, its time for him to seek his revenge.

In this program, the heros inventory is represented by an array. The array is a sequence of string objectsone for each item in the heros possession. The hero trades and even finds new items. Figure 3.4 shows the program in action.

You can download the code for this program from the Course Technology website (www.courseptr.com/downloads). The program is in the Chapter 3 folder; the filename is heros_inventory.cpp.

Using Arrays 97



image

Figure 3.4

The hero’s inventory is a sequence of string objects stored in an array.


// Hero’s Inventory

// Demonstrates arrays


#include <iostream> #include <string>

using namespace std; int main()

{

const int MAX_ITEMS = 10; string inventory[MAX_ITEMS];


int numItems = 0; inventory[numItems++] = "sword"; inventory[numItems++] = "armor"; inventory[numItems++] = "shield";


cout << "Your items:\n";

for (int i = 0; i < numItems; ++i)

{

cout << inventory[i] << endl;

}

98 Chapter 3 n For Loops, Strings, and Arrays: Word Jumble


cout << "\nYou trade your sword for a battle axe."; inventory[0] = "battle axe";

cout << "\nYour items:\n";

for (int i = 0; i < numItems; ++i)

{

cout << inventory[i] << endl;

}


cout << "\nThe item name ’" << inventory[0] << "’ has "; cout << inventory[0].size() << " letters in it.\n";


cout << "\nYou find a healing potion."; if (numItems < MAX_ITEMS)

{

inventory[numItems++] = "healing potion";

}

else

{

cout << "You have too many items and can’t carry another.";

}

cout << "\nYour items:\n";

for (int i = 0; i < numItems; ++i)

{

cout << inventory[i] << endl;

}


return 0;

}