Subprograms in arrays

I don't know if it's even possible to put subprograms in arrays, such as items in an in-game shop.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
  struct user
{
string username;
int hp;
int hunger;
int money;
}
void eatfood(food, hunger)
{
hunger = hunger - food;
food = 0;
}
void eat(int hunger, string item[int size])
{
int food;
for (int i=0;i<size;i++)
{
//This doesn't have to be read; all it is is a loop for eating and getting full.
if(item[i] == "Apple") || (item[i] == "Fruit")
{food = 2;
eatfood(food, hunger)
}
if(item[i] == "Steak") || (item[i] == "Salad")
{
food = 4;
eatfood(food, hunger)
}
if(item[i] == "Cheese wedge") || (item[i] == "Burger")
{food = 5;
eatfood(food, hunger)}
}
}
void starve(int hunger, int hp)
//Do stuff

void shop(int gold)
{
string answer;
int shopcost[6] = {2, 4, 6, 5, 7, 8}
string shopkeeper[6] = {"Apple", "Fruit", "Steak", "Salad", "Cheese wedge", "Burger"}
for (int i = 0; i<6; i++)
{
cout << "Money = " << gold << endl;
cout << "Item = " << shopkeeper[i] << endl;
cout << "Cost = " << shopcost[i] << endl;
cout << "BUY?" << endl;
cin >> answer
//if answer = BUY then do stuff
}
}
}

How would you relate the shopcost array to the shopkeeper array?
Use a struct? Class? Pointers?
Last edited on
I don't understand the question. What do you mean "relate"?
Relate as in connect them, so that I don't have to put the arrays individually,

example:

1
2
cout << "Item, and cost, = " << bothArrays[i] << endl;
//so that I can print both the item name and cost at the same time. 


So, if bothArrays[0] = ("Apple, cost ", 5)

then the output of the code above is:

 
Item, and cost, = Apple, cost 5
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
struct Item{
    std::string name;
    int cost;
};

Item items[] = {
    { "Apple", 2 },
    // etc.
};

for (int i = 0; i < 6; i++)
    std::cout <<items[i].name<<", "<<items[i].cost<<std::endl;
    // If operator<<(std::ostream &, const Item &) was overloaded,
    // you could also do
    // std::cout <<items[i]<<std::endl; 
Last edited on
Thanks!
Topic archived. No new replies allowed.