Jump to content

  • Log In with Google      Sign In   
  • Create Account

looping through struct array


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • You cannot reply to this topic
3 replies to this topic

#1 JonathanCCC   Members   -  Reputation: 158

Like
0Likes
Like

Posted 20 July 2014 - 03:26 PM

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;
    }
}

Edited by JonathanCCC, 20 July 2014 - 03:29 PM.


Sponsor:

#2 Zaoshi Kaba   Crossbones+   -  Reputation: 4592

Like
1Likes
Like

Posted 20 July 2014 - 03:42 PM

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.



#3 Washu   Senior Moderators   -  Reputation: 5423

Like
3Likes
Like

Posted 20 July 2014 - 05:31 PM

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();
}

Edited by Washu, 20 July 2014 - 05:33 PM.

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.
ScapeCode - Blog | SlimDX


#4 JonathanCCC   Members   -  Reputation: 158

Like
0Likes
Like

Posted 21 July 2014 - 11:27 AM

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

 

Thanks for the sample!






Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS