C++中的并行数组

0 c++ arrays

我有一个任务,我们需要有2个并行数组,一个是城市名称列表,另一个是销售额.这是问题的副本:

项目描述:

它需要编制美国各个城市的销售总额.具体而言,当程序运行时,将提示用户进入城市.如果城市正确,则会提示用户输入销售额.如果列表中不存在该城市,则用户将收到错误消息(并且没有销售额提示).如果输入销售金额,它将累计为该城市的总金额.无论哪种方式(城市是否存在于列表中),用户将被要求进入另一个城市或退出.用户退出后,应显示所有城市的城市名称和总数,每行一个.之后程序应该停止.

只有8个城市可供选择.必须使用2个并行数组,初始化如下:

City (String)  Sales (Integer)
-------------  ---------------
Atlanta              0
Buffalo              0
Chicago              0
Dallas               0
Houston              0
Honolulu             0
Miami                0
Reno                 0
Run Code Online (Sandbox Code Playgroud)

所有输入都保证是单字,然后只输入.它可能与城市名称不匹配,但不会有空格.这使您的程序简单,因为它可以避免使用getline(),这将需要处理单词之间的空白.输入时保证销售数据良好.

当我试图运行我的程序时,视觉工作室变得疯狂,我已经拔出我的头发试图解决它.如果有人可以帮我提一下我做错了什么,我会非常感激.这是我的程序的副本:

#include <iostream>
#include <string>

using namespace std;

int main()
{
    //declare city and sales array
    string city[8] = {" "};
    int sales[8] = {0};

    //declare variables
    string cityName = " ";
    int cityTotal = 0;
    int salesAmt = 0;
    int i = 0;
    char another = ' ';

    //init city array
    city[0] = "Atlanta";
    city[1] = "Buffalo";
    city[2] = "Chicago";
    city[3] = "Dallas";
    city[4] = "Houston";
    city[5] = "Honololu";
    city[6] = "Miami";
    city[7] = "Reno";

    do
    {
        //input city name and if found input sales amount
        cout << "Enter a City: Atlanta, Buffalo, Chicago, Dallas, Houston, Honololu, Miami, or Reno: ";
        cin >> cityName;

        for(i = 0; i <= 8; i++)
        {
            if(cityName == city[i])
                {cout << "Enter sales amount: ";
                 cin >> salesAmt;
                 salesAmt += sales[i];}
            else
                {cout << "ERROR: CITY NOT AVAILIABLE" << endl;
                 cout << endl;}
            //end if
        }
        //end for loop

        //ask if another city
            cout << "Enter another city?: ";
            cin >> another;

    } //end do loop
    while(another == 'Y' || another == 'y');
    {
        for(i = 0; i <= 8; i++)
        {
            cout << "City: " << "           " << "Sales: " << endl;
            cout << city[i] << "          " << sales[i] << endl;
        }
        //end for loop
    } //end while loop

    system("pause");
    return 0;
} //end of main
Run Code Online (Sandbox Code Playgroud)

Nas*_*sim 6

这里明确的错误是您使用索引访问数组的方式,您不能让for循环达到8,因为数组的索引最多只有7个.将for循环更改为:

for(i = 0; i < 8; i++)
Run Code Online (Sandbox Code Playgroud)