コードを実行するたびに、文字列の添え字が範囲外であるというエラーが表示されます (エラー メッセージはタイトルです)。「カウンター」を使用して都市の総数と平均人口を計算するためだと思います。これを修正するにはどうすればよいですか?私はそれを計算するために他の方法を試しましたが、どれもうまくいきませんでした。
void cities( istream& in, ostream& out )
{
ifstream ("cities.txt");
string country, city, city2, state, lat, longi;
int pop;
int currentPop = 0;
int smallestPop = 0;
int largestPop = 0;
int counter = 0;
int sum = 0;
int i = 0;
int average = 0;
string largestCity;
string smallestCity;
string population;
readLineOfData(in, country, city, city2, state, pop, lat, longi);
while(!in.fail())
{
counter++;
output( out, country, city, city2, state, pop, lat, longi );
readLineOfData(in, country, city, city2, state, pop, lat, longi);
population[counter] = pop;
if (pop < smallestPop || smallestPop == 0)
{
smallestPop = pop;
smallestCity = city2;
}
if (pop > largestPop || largestPop == 0)
{
largestPop = pop;
largestCity = city2;
}
for (int i = 0; i<counter; i++)
{
sum += population[i];
average = sum/counter;
}
}
out << "Smallest City: " << smallestCity << endl;
out << "Population: " << smallestPop << endl;
out << endl;
out << "Largest City: " << largestCity << endl;
out << "Largest Population: " << largestPop << endl;
out << endl;
out << "Total Cities: " << i << endl;
out << "Average Population: " << average << endl;
return;
}
void readLineOfData( istream& in, string &country, string &city, string &city2,
string &state, int &pop, string &lat, string &longi)
{
getline( in, country, ',');
getline( in, city, ',');
getline( in, city2, ',');
getline( in, state, ',');
in >> pop;
in.ignore( 200, ',' );
getline( in, lat, ',');
getline( in, longi, '\n' );
}
void output( ostream& out, string country, string city, string city2,
string state, int pop, string lat, string longi )
{
}