0
每當我運行我的代碼時,出現一個錯誤,指出我的字符串下標超出範圍(錯誤消息是標題)。我預計它是從使用「櫃檯」來計算總城市和平均人口。我該如何解決這個問題?我嘗試過其他方法來計算它,但都沒有工作。表達式:字符串下標超出範圍
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)
{
}
錯誤信息? – uba 2013-03-09 05:47:38
來自標題 – user2145500 2013-03-09 05:48:07
的人口是單個字符串或字符串數組 – Riskhan 2013-03-09 05:48:20