I have constructed a class for matrix in C++ and I'm not able to retrieve the values from a matrix stored in a txt file. This is the matrix format I'm working with:
4 4
3.14 1.59 2.65 3.58
9.79 3.23 8.46 2.64
3.38 3.27 9.50 2.88
4.19 7.16 9.39 9.37
The first line is rows and cols, respectively. My header file Matrix.h looks like this
#ifndef __MATRIX__CLASS__TYPE
#define __MATRIX__CLASS__TYPE
#include <iostream>
#include <fstream>
#include <stdlib.h>
class Matrix
{
private:
unsigned nRows;
unsigned nCols;
double **mArray;
public:
// Create a matrix based on a txt file
Matrix(const char *);
// Destructor
~Matrix();
// Accessing to the Matrix data
unsigned getRows() const;
unsigned getCols() const;
double** getArray() const;
void printArray() const;
};
#include "matrix.cpp"
#endif
My matrix.cpp file looks like this:
// Constructor for the
Matrix::Matrix(const char *fileName)
{
// Start by opening the .txt where the matrix is stored
std::ifstream fileArray(fileName);
std::string lineFile;
double cellValue;
// Set the counter for indexing the array
unsigned i = 0;
unsigned j = 0;
int rows, cols;
if (fileArray.is_open() && fileArray.good())
{
while (getline(fileArray, lineFile))
{
// std::cout << lineFile << std::endl;
std::stringstream streamArray(lineFile);
j = 0;
while (1)
{
streamArray >> cellValue;
if (!streamArray)
break;
// Retrieve meta data
if (i == 0 && j == 0)
{
rows = (int) cellValue;
nRows = rows;
// Initialize the array given the row values were already retrieved
mArray = new double *[rows];
j += 1;
}
else if (i == 0 && j == 1)
{
cols = (int) cellValue;
nCols = cols;
j += 1;
}
else if (cols > 0)
{
// Fill values
mArray[i - 1] = new double[cols];
mArray[i-1][j] = cellValue;
j += 1;
}
}
i += 1;
}
}
// Close file
fileArray.close();
}
// Getter for matrix rows
unsigned Matrix::getRows() const
{
return this->nRows;
}
// Getter for matrix cols
unsigned Matrix::getCols() const
{
return this->nCols;
}
// Getter for the array entrys
double **Matrix::getArray() const
{
return this->mArray;
}
void Matrix::printArray() const
{
for (unsigned i = 0; i < nRows; i++)
{
for (unsigned j = 0; j < nCols; j++)
{
std::cout << mArray[i][j] << "\t";
}
std::cout << std::endl;
}
}
When I check for the values in mArray[i-1][j] individually while I'm still in the loop, it looks like it successfully stored the data in the variable. However, once I print the array using the prin method (printArray()) it returns the default values for creating a double-type array and only the last column is modified as I show in the following example:
1.27553e-311 1.27553e-311 0 3.58
1.27553e-311 1.27553e-311 8.99755e-91 2.64
0 0 0 2.88
0 0 0 9.37