Read matrix from file

Feb 27, 2018 at 11:26pm
Hi, i want to read a matrix that can take double values but my program is crashing, can you help me please? Thanks!

Here is my code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
void Matrix::Load(char* matrixroute)
{
	ifstream file;
	file.open(matrixroute);

	int size[2]; //0=rows, 1=columns,
	for(int i=0; i<3;i++)
	{
		file >> size[i];
	}
	
	double Matrix[size[0]][size[1]];

	for (int i = 0; i < size[0]; i++)
	  {
	  for (int j = 0; j < size[1]; j++)
	    {
	    file >> Matrix[i][j]; //problem is at this line
	    }
	  }
	file.close();
}


txt file (matrix):
1
2
3
4
5
6
4
4
1 2 3 4
2 4 5 6
3 5 6 7
4 6 7 8


Could you also please help me transforming this program for using dynamic memory? Thanks!
Last edited on Feb 27, 2018 at 11:35pm
Feb 27, 2018 at 11:58pm
Tested on Ubuntu and now is working (Windows didnt worked), do you know why this issue happened?
Feb 28, 2018 at 4:59pm
Sometimes in cases like this, it's helpful to check for an "off-by-one" or indexing error. Since your example matrix file has two lines different from the rest, this part looks suspicious:
1
2
3
4
5
int size[2]; //0=rows, 1=columns,
for(int i=0; i<3;i++)
{
    file >> size[i];
}

i<3 means it will run for i=0, i=1, i=2. Three times. Setting it to i<2 will probably fix later matrix filling problems.
Feb 28, 2018 at 5:34pm
The following is also not allowed in a C++ program: double Matrix[size[0]][size[1]];. Array sizes must be compile time constants in C++. A properly configured compiler should warn you about this issue.


Feb 28, 2018 at 6:56pm
As far as using "dynamic" memory I suggest something similar to the following:

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
class Matrix
{
    public:
        void load(const std::string& matrixroute);
    private:
        int row, col;
        std::vector<std::vector<double>> matrix;
};

void Matrix::load(const std::string& matrixroute)
{
    std::ifstream file(matrixroute);
    if(!file)
    {
        std::cerr << "Error opening matrix file.\n";
        return;
    }

    file >> row >> col;
    if(row < 1 || col < 1)
    {
        std::cerr << "Matrix sizes are out of bounds.\n";
        return;
    }

    // Size the vector using the values read from the file.
    matrix.resize(row);
    for(auto& m : matrix)
        m.resize(col);

    // Read the input file.
    for(auto& outer : matrix)
        for(auto& inner : outer)
            file >> inner;

}


Topic archived. No new replies allowed.