Creating a 2d array matrix from getting the row and column from a file

I am trying to create a 2d array matrix, but I don't get the row and column until I open a file. I was curious as to how I could do it and still make the array visible outside of the while loop. Here is how I am reading the file and inserting into a 2D array (but gives an error when creating the array). I MUST use an array, unfortunately.
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
  string line = "";
	string currentValue = "";
	double nextMatrixValue = 0;
	int lineCounter = 0;
	int rank = 0;
	vector<double> matrixValues;
	int numOfRightHandSides = 0;
	vector<double> rightHandSides;
	ifstream myStream;
	myStream.open(argv[1]);
	while (!myStream.eof()) {//read line by line
		getline(myStream, line);
		stringstream ss(line);
		if (lineCounter == 0){ 
			//get the rank (number of rows and columns)		
			rank = stoi(line);
			lineCounter++;
		}
		else if (lineCounter <= rank) {
			//get matrix values for each row
			stringstream ss(line);
			vector<double> matrixRow;
			while (ss >> currentValue) {
				matrixRow.push_back(stod(currentValue));
			}
			for each(double value in matrixRow) {
				matrixValues.push_back(value);
			}
			lineCounter++;
		}
		else if (lineCounter == rank + 1) {
			//get right hand sides
			numOfRightHandSides = stoi(line);
			lineCounter++;
		}
		else if (lineCounter >= rank + 2) {
			stringstream ss(line);
			vector<double> rightHandRow;
			while (ss >> currentValue) {
				rightHandRow.push_back(stod(currentValue));
			}
			for each(double value in rightHandRow) {
				rightHandSides.push_back(value);
			}
		}
	}
        const int TOTAL = matrixValues.size()/rank;//get total row & columns
	//make a 2d array
	double originalArray[TOTAL][TOTAL];            //ERROR HERE (Must be a constant value)
	for (int i = 0; i < TOTAL; i++) {
		//insert values into each array position
		for (int j = 0; j < TOTAL; j++) {
			//insert values for row into vertical array position
			double nextVecVal = matrixValues.front();
			matrixValues.erase(matrixValues.begin());
			originalArray[i][j] = nextVecVal;
		}
	}
Last edited on
closed account (iN6fizwU)
Is TOTAL really allowed to be 'const'? Surely it depends on your input at run-time.

Since TOTAL is determined at run-time (rather than compile-time) you may need to use new to allocate originalArray.
Topic archived. No new replies allowed.