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 )
{
}
4

1 回答 1

2

宣言

string population;

表示这population是一个字符代码序列,但您将其视为一个数字序列:

population[counter] = pop;

此时它的大小也是 0,因此索引只会出错或给出未定义的行为。

相反,声明population为 astd::vector并使用

population.push_back( pop );
于 2013-03-09T05:52:11.323 回答