[Solved] How can I iterate through a array filled with structures?


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", 11, 2017, 11.0, 1}, 
    { "Mike", 10, 2015, 10.0, 1} 
};

int main()
{
    for( const auto& state : States )
    {
        std::cout << state << '\n';
    }

    std::cout << '\n';

    for( auto i = 0u; i < sizeof( States ) / sizeof( PlayerState ); ++i )
    {
        std::cout << States[i] << '\n';
    }
}

2

solved How can I iterate through a array filled with structures?