Adding Values in an Array

I'm currently having problems with this program. The program is to take data the sales records from a file and add them together if the sales are from the same month. So far I have these two functions written up:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
//********************************************************************************
void buildSalesArray(double salesArray[])
	{
	ifstream inFile;
	int month = 0;
	double sales;
	
	inFile.open("sales.txt");
	if (!inFile)
    	{
    	cout << "Error - unable to open input file\n";
    	exit(1);
    	}
		
	while (inFile)
		{
		inFile >> month;
		inFile >> sales;
		salesArray [month] = sales;
		month++;
		}
	inFile.close();	   
	}
	
//********************************************************************************
void printSalesArray(double salesArray[])
	{
	int month;
	cout << fixed << setprecision(2);
	
	for (month = 1; month < NUMBER_OF_MONTHS + 1; month++)
		{
		cout << salesArray [month] << endl ; 
		}
	} 
	
//******************************************************************************** 


However I run into a problem when I get sales from similar month in which the most recent data over rides the previous totals. I was wondering if anybody could give me some direction on how to add the totals together in the Array.

Edit: I also noticed that the 5th element of the array is being duplicated onto the 6th.

i.e: If 5 reads 312.12, 6 will read the same
Fixed

Last edited on
Well, if you want to sum up the numbers, you have to use operator+ somewhere :)

Line 19 of your code should be changed to:
 
salesArray [month] += sales; // += instead of = 


Two more things: don't forget to initialize your array with zeroes and you don't need line 20 (month++) because it adds 1 to the variable month, which is overwritten in the next loop iteration by reading it from file.

Edit:
It looks like you start indexing the salesArray from 1. While I understand that it makes it easier to read the data from file, it is not a good practice (in C++ the array indexing starts from 0). To fix that - you should change line 19 to salesArray [month - 1] = sales; and your output loop to:
1
2
3
for (month = 0; month < NUMBER_OF_MONTHS; month++) {
	cout << salesArray [month] << endl ; 
}
Last edited on
Topic archived. No new replies allowed.