c++ - add value from file to double pointer -
my .h file
#ifndef adjacencymatrix_h_ #define adjacencymatrix_h_ #include <iostream> #include <fstream> #include <cstring> #include <cstdio> #include <cstdlib> using namespace std; class adjacencymatrix{ private: int vertexcount; int vertexfirst; int edgecount; int **wage; int **matrix; public: adjacencymatrix(); virtual ~adjacencymatrix(); bool createfromfile(string path); void viewmatrix(); }; #endif /* adjacencymatrix_h_ */
i read form file , want write initialized matrix, doesn’t work. can me ?
#include "adjacencymatrix.h" adjacencymatrix::adjacencymatrix() { this->vertexcount=0; this->vertexfirst=-1; this->edgecount=0; } adjacencymatrix::~adjacencymatrix() { } bool adjacencymatrix::createfromfile(string path) { fstream file; file.open(path.c_str(), fstream::in); if (file.good()) { int vertexf,vertexe,wag; cout << "file opened" << endl; file >> this->edgecount; file >> this->vertexcount; file >> this->vertexfirst; matrix = new int *[edgecount]; wage = new int *[edgecount]; (int = 0; < vertexcount; i++) { matrix[i]=new int[edgecount]; wage[i]=new int[edgecount]; } //fill matrix zeros (int = 0; < vertexcount; i++) { for(int j=0; j<edgecount;j++) { matrix[i][j]=0; wage[i][j]=0; } } // fill matrix 1 for(int i=0; i<edgecount; i++) { file >> vertexf >> vertexe >> wag; cout << " w " << wag; matrix[vertexf][vertexe] = 1; } file.close(); return true; } cout << "file not opened" << endl; return false; } void adjacencymatrix::viewmatrix(){ cout << " adjacency matrix "; for(int i=0; i<vertexcount; i++) { for(int j=0; i<edgecount;i++) { cout << this->matrix[i][j] << " "; } cout<< endl; } }
and part not work(i mean, nothing display , showmatrix() not work). want value file , write matrix[x][y] = 1
because want create graph path.
for(int i=0; i<edgecount; i++) { file >> vertexf >> vertexe >> wag; // cout work in line matrix[vertexf][vertexe] = 1; // not work }
the size of matrix wrong:
matrix = new int *[edgecount]; // wrong size wage = new int *[edgecount]; // wrong size (int = 0; < vertexcount; i++) { matrix[i]=new int[edgecount]; wage[i]=new int[edgecount]; }
when define matrix should use vertexcount
instead, this:
matrix = new int *[vertexcount]; wage = new int *[vertexcount];
this might lead segmentation faults or strange behaviour.
also, when read data provided user should validate them:
file >> vertexf >> vertexe >> wag; matrix[vertexf][vertexe] = 1;
are sure vertexf
, vertexe
aren't larger vertexcount - 1
, edgecount - 1
?
Comments
Post a Comment