Searching Array of structs

In C++, I have to read zip codes from a file. While there are zip codes in the file, I need to search the array (of Structs) until either a matching zip code or the "end" of the array has been found. If the zip code exists in the array, I have to increment the appropriate count by 1. If not, I have to put the zip code into the array at the "end" and set the count to 1. Then I have to get the next zip code from the input file. Here's my code so far:

/***************************************************************
Function: buildArray

Use: This function will read the file of data and fill
the array.

Arguments: 1. City[] : array of City structures

Returns: number of valid cities that were in the input file
***************************************************************/
int buildArray( City cityAr[] )
{
ifstream inFile;
int num, i;

i = 0;

inFile.open( "zipcodes.txt" );
if( inFile.fail() )
{
cout << "file failed to open" << endl
<< system( "pause" );
exit( -1 );
}

inFile >> num;

while( inFile )
{
if( num == cityAr[i].zip_code )
{
cityAr[i].count ++;
i++;
}
else
{
cityAr[i].zip_code = num;
cityAr[i].count = 1;
i++;
}
inFile >> num;
}

inFile.close();

return i;

}

This code results in 560 individual lines of zip codes. Any duplicates in the file should not be added again, but rather, incremented in their cityAr[i].count

Thanks in advance for your help!
BR

Awesome. What do you want help with?

-Albatross
I'm trying to figure out how to get the correct counts incremented without the duplicate zipcodes being added to the array again.

-BR
Oh, that's easy. Just feed all the elements into a set.

http://cplusplus.com/reference/stl/set/

EDIT: I'll happily provide help with sets if need be.

-Albatross
Last edited on
Topic archived. No new replies allowed.