Advertisement

looping through struct array

Started by July 20, 2014 09:26 PM
2 comments, last by JonathanCCC 10 years, 6 months ago

I'm trying to get a print out of inventory items, so that it prints out the items prefixed with 1. 2. 3. etc.

I'm not sure how best to loop through these kind of arrays, so I tried a stupid fix with the currentinv variable which I'm sure is unnecessary smile.png

If anyone can suggest the best loop code for the display inventory function I'd be grateful


struct character
{
    string name;
    unsigned short int health = 100;
    unsigned short int currentinv = 4;
    string inventory[10] = {"Gun", "Knife", "Blade"};
} player;

void displayinventory()
{
    string *elem = &player.inventory[0];
    for (unsigned short int i = 1; i < player.currentinv; ++i)
    {
        cout << "\n" << i << ". " << *elem << "\n\n";
        ++elem;
    }
}

Well that's more or less correct thinking.

Use vector<string> which doesn't have size limit and you can retrieve number of items without making own extra variable.

Advertisement
There's a few different ways to do this, you can use a vector of strings (or deque), if you're using C++11 then you can use the ranged base for, but if you want the items numbered then standard for loop probably works best... sample below...

#include <iostream>
#include <string>
#include <vector>

struct character
{
	unsigned int health;
	std::vector<std::string> inventory;
};

void displayinventory()
{
	character player = { 100, { "Gun", "Knife", "Blade" } };
	for (size_t i = 0; i < player.inventory.size(); ++i)
	{
		std::cout << i << ". " << player.inventory[i] << std::endl;
	}
}

int main() {
	displayinventory();
}

In time the project grows, the ignorance of its devs it shows, with many a convoluted function, it plunges into deep compunction, the price of failure is high, Washu's mirth is nigh.

thanks, I am using C++11 so I'll go with the vector :)

Thanks for the sample!

This topic is closed to new replies.

Advertisement