Mike van den Hoek Mike van den Hoek - 4 years ago 89
C++ Question

How can I iterate through a array filled with structures?

I'm trying to learn c++ for just a week now.
I want to iterate through a array filled with structures.
This is the code that I have.

struct PlayerState
{
char name[20];
int level;
int year;
double health;
int experience;
};

PlayerState States[2] = {
{ "Mike", 10, 2017, 10.0, 1},
{ "Mike", 10, 2017, 10.0, 1}
};


How can I using a for loop to show the output of this array?

Answer Source

If you'll do it often, define a stream operator for your struct, then loop over them (see it live on Coliru):

#include <iostream>

struct PlayerState
{
    char name[20];
    int level;
    int year;
    double health;
    int experience;
};

std::ostream& operator<< ( std::ostream& os, const PlayerState& state )
{
    os << state.name << ": " 
       << state.level << ", " 
       << state.year<< ", " 
       << state.health << ", " 
       << state.experience;
    return os; 
}

PlayerState States[2] = { 
    { "Mike", 10, 2017, 10.0, 1}, 
    { "Mike", 10, 2015, 10.0, 1} 
};

int main()
{
    for( const auto& state : States )
    {
        std::cout << state << '\n';
    }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download