Summing a 2D array's columns

Apr 30, 2017 at 4:19pm
I'm trying to sum the first 4 columns of a 2D array but I keep getting the wrong answer. I'm pulling the 2D array data from a file then making a nested for loop to accomplish the math. I should be getting 1644393 for the number of visitors but I'm getting -2147483648. So I'm not exactly sure what I'm doing wrong here. Any help would be much appreciated. I'm still very new at coding also.

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
  void totalVisitors()
{
	ifstream inputVisitors_File;
		
	inputVisitors_File.open("Visitors.txt");

	int visitorsTotal = 0;
	double visitors[VISITOR_ROWS][VISITOR_COLS];
		
	for (int rows = 0; rows < VISITOR_ROWS; rows++)
	{
		for (int cols = 0; cols < VISITOR_COLS; cols++)
		{
			inputVisitors_File >> visitors[VISITOR_ROWS][VISITOR_COLS];
			//cout << setw(10) << visitors[VISITOR_ROWS][VISITOR_COLS];
		}
		//cout << endl;
	}
	
	for (int col = 0; col < 4; col++)
	{
		for (int row = 0; row < VISITOR_ROWS; row++)
			visitorsTotal = visitorsTotal + visitors[row][col];
	}

	cout << endl << "The total is: " << visitorsTotal << endl;

	inputVisitors_File.close();
}
Apr 30, 2017 at 4:34pm
Sometime negative number happens is because of that it cannot hold that big of a number, like in a int it Can only hold certain amount of values. You might as well check that.
Apr 30, 2017 at 5:02pm
On line 14 you are reading everything into the same point in memory (which is also outside your array bounds). VISITOR_ROWS and VISITOR_COLS are the number of values for each index. Try reading into
visitors[rows][cols] instead.
Apr 30, 2017 at 5:37pm
That fixed it! Thanks so much, you're a life saver! My logic was that since VISITOR_ROWS and VISITOR_COLS are the same value as rows and cols it should work fine. Big time wrong on that one. Thanks again.
Topic archived. No new replies allowed.