Mourneris
Mourneris

Reputation: 33

Nested For Loop (C++) Not Working Properly

I am working on some programming homework and I am trying to use a for-loop in order to facilitate the process of the coding. Here is the loop:

#ifndef DIVSALES_H
#define DIVSALES_H

class DivSales
{
    public:
        DivSales(){ quarterSales[4] = {0}; };
        double getTotalSales() { return totalSales;}
        static void setTotalSales(double);
        static void addTotalSales(double);
        double getQuarterSales(int numQuarter) {return quarterSales[numQuarter];}
        void setQuarterSales(int numQuarter, double numAmount) { quarterSales[numQuarter] = numAmount;}
    private:
        static double totalSales;
        double quarterSales[];
};

double DivSales::totalSales = 0;
void DivSales::setTotalSales(double totalAmount) {totalSales = totalAmount; }
void DivSales::addTotalSales(double addAmount) {totalSales += addAmount; }
#endif // DIVSALES_H

#include <iostream>
#include "DivSales.h"

using namespace std;

int main()
{
    const int NUMDIVS = 6;
    const int NUMQUARTERS = 4;
    double amount = 0;

    DivSales divs[NUMDIVS];

    for(int division = 0; division < NUMDIVS; division++)
    {
        cout << "Division " << (division + 1) << endl;

        for(int quarter = 0; quarter < NUMQUARTERS; quarter++)
        {
            cout << "Quarter " << (quarter + 1) << ": ";
            cin >> amount;

            divs[division].setQuarterSales(quarter, amount);
            DivSales::addTotalSales(amount);
        }
    }


    return 0;
}

Example of the output:

Division 1
Quarter 1: 500
Quarter 2: 500
Quarter 3: 500
Quarter 2: 500
Quarter 3: 500
Quarter 2: 500
Quarter 3: 500
Quarter 2: 500
Quarter 3: 500
Quarter 2: 

What I am trying to do is make it so that when I have input the numbers for the 4 quarters of a division, that it will move onto the next division. However, after 4 inputs it is not incrementing the division variable of the for-loop instead it continues asking for more inputs. What is going on?

Upvotes: 2

Views: 1335

Answers (2)

memo1288
memo1288

Reputation: 738

I have found what's causing that problem, it is in the file DivSales.h:

Change this line:

double quarterSales[];

For this line:

double quarterSales[4];

The problem was that you were not allocating memory for an array of 4 elements. To initialize it, change your constructor to this:

DivSales():quarterSales({0}){ };

You should also move the following line to DivSales.cpp, because otherwise I was getting a multiple definition error:

double DivSales::totalSales = 0;

Upvotes: 2

Sarien
Sarien

Reputation: 6992

Here:

divs[division].setTotalSales(amount);

you probably want:

divs[division].addTotalSales(amount);

But that is not what is causing your problem. Which I cannot reproduce.

Upvotes: 0

Related Questions