-1

The program's purpose is to fill two arrays from data in a file, the first column is department number, and the second is boxes sold. There should be a max of 15 departments, variables departmentNumber and boxesSold should receive data from file before filling array

#include <iostream>
#include <string>
#include <fstream>

using namespace std;

int main()
{
    int departmentNumber = 0, boxesSold = 0;

    ifstream inputFile("boxes.txt");

    const int SIZE = 15;
    int departmentArray[SIZE];
    int boxesArray[SIZE];

    int count = 0;

    while (count < SIZE && inputFile);
    {
        inputFile >> departmentNumber;
        inputFile >> boxesSold;

        for (int index = 0; index < count; index++)
        {
            if (departmentArray[index]== departmentNumber)
            {
                boxesArray[index] = boxesArray[index] + boxesSold;
            }
            else
            {
                departmentArray[index] = departmentNumber;
                boxesArray[index] = boxesSold;
                count++;
            }

        }
        inputFile.close();
    }

    //display numbers
    for (int i = 0; i < count; i++)  
    { 
        cout << departmentArray[i] << " "; 
        cout << boxesArray[i];
        cout << endl;   
    }
    system("pause");
}

current output is blank. my for loop searches array to see if departmentNumber already exist, my while loop continues to accept data from file, and the last for loop displays number. Been stuck on this for too long.

 int count = 0;

        while (count < SIZE && inputFile)
        {
            inputFile >> departmentNumber;
            inputFile >> boxesSold;

            for (int index = 0; index < count; index++)
            {
                if (departmentArray[index] == departmentNumber)
                {
                    boxesArray[index] = boxesArray[index] + boxesSold;

                }
                else
                {
                    departmentArray[count] = departmentNumber;
                    boxesArray[count] = boxesSold;

                }
             }
            boxesArray[count] = boxesSold;
             count++;
        }
            inputFile.close();

i updated the code and the following output is given, my guess is the for loop, that or index/count is not declared properly,

-858993460 23
410 17
410 16
120 14
150 32
300 27
410 11
410 10
120 8
150 16
120 2
300 4
410 5
520 6
390 7
Press any key to continue . . .
4

1 回答 1

0

当你第一次开始时,你没有处理这个案子。什么时候发生count = 0?你永远不会进入for循环。

我建议一种更简单的方法是使用std::map<int, int>. 在你的读取循环中做这样的事情:

map[departmentNumber] += boxesSold;

这将执行以下操作:

  1. 如果departmentNumber存在于地图中,它会增加boxesSold.
  2. 如果departmentNumber地图中不存在 ,则将其添加等于 0 的值,然后将其递增boxesSold
于 2015-11-24T04:28:22.913 回答