Accessing a struct within a struct
I'm required to use 2 specific structs and I'm not sure how I'm able to use the struct that's inside another. I need to access a .txt file and store the information in state and county arrays.
Example file contents:
state_1_name population #_counties
county_1_name population county_income household_income #_cities city_1name city_2_name
county_2_name population county_income household_income #_cities city_1name city_2_name
state_2 ... etc.
structs:
struct county
{
string name;
string *city;
int cities;
int population;
float avg_income;
float avg_house; // average household income;
};
struct state
{
string name;
struct county; //In my actual program I have *c declared, which is why my code below has states.c
int counties;
int population;
};
We weren't given a variable for county inside state, so I don't know how to access it without creating one, but we were given specific instructions that we need to use the structs and prototypes exactly as given. Once I've gone through getting the state information and placing it inside an array i need to get the county(ies) information. How am I to have a pointer in the state array point to the county information for that state?
Get data functions:
void get_state_data(state *states, int numStates, ifstream &file)
{
for (int i = 0; i < numStates; i++)
{
file >> states[i].name >> states[i].population >> states[i].counties;
states[i].c = create_counties(states[i].counties);
}
}
void get_county_data(county *counties, int numCounties, ifstream &file)
{
for (int i = 0; i < numCounties; i++)
{
file >> counties[i].name >> counties[i].population >> counties[i].avg_income
>> counties[i].avg_house >> counties[i].cities;
counties[i].city = new string[counties[i].cities];
for (int j = 0; j < counties[i].cities; j++)
file >> counties[i].city[j];
}
}
2 comments · 100% upvoted · other discussions
The definition you were given for the
statestruct wasn't correct. You were right that the field needs a name. Check with the instructor.The
countyfield could just be a single value, could be an array, could be a pointer. It shouldn't be an unnamed field, though.WHOAREYOUANDWHEREAMI [OP] 1 points · Apr 2016
That's what I thought and have been doing but I wasn't sure if I was just missing something. Thanks for the confirmation.