### taking input from a file (graph)

Hi,

So I need to represent a graph using adjacency matrix.The number of vertices and edges I have to read them from a file data.txt
Here is the file

 ``12345678910111213141516171819`` ``````6 9 // 6= nr of vertices; 9=nr of edges 1 2 2 // edge 1 edge 2 cost 1 3 4 // edge 1 edge 3 cost 2 3 1 // edge 2 edge 3 cost 2 4 4 2 5 2 3 5 3 4 6 2 5 4 3 5 6 2 5 7 // 5= nr of vertices; 7=nr of edges 1 2 10 1 4 30 1 5 100 2 3 50 3 5 10 4 3 20 4 5 60``````

Here is my code.
 ``1234567891011121314151617181920212223242526272829303132`` `````` #include #include using namespace std; int main() { ifstream infile("data.txt"); int n,m; int a,b,c; int cost[100][100]; for(int i=0;i>n>>m) { while (infile>>a>>b>>c) { for(int i=0;i

The problem is that my code prints the matrix just for the first set of data.What I have to do such that the program prints the second matrix?
A simple loop would work. Keep looping until the of the file is reached.

For good, readable program structure, I'd advise putting all the code that reads a single matrix into a function, and then call that function on each iteration of the loop.
Are you sure that your graph isn't undirected?

Your data seems to correspond to TWO graphs?

 ``1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768`` ``````#include #include #include #include using namespace std; class Graph { int numVert; vector< vector > adj; public: Graph( istream &in ); void write( ostream &out ); }; Graph::Graph( istream &in ) { int nedge, a, b, cost; in >> numVert >> nedge; adj = vector< vector >( numVert, vector( numVert, 0 ) ); for ( int i = 0; i < nedge; i++ ) { in >> a >> b >> cost; adj[a-1][b-1] = cost; // adj[b-1][a-1] = cost; // need this as well if graph is undirected } } void Graph::write( ostream &out ) { for ( int i = 0; i < numVert; i++ ) { for ( int j = 0; j < numVert; j++ ) out << setw( 2 ) << adj[i][j] << ' '; out << '\n'; } } //====================================================================== int main() { istringstream in( "6 9 \n" "1 2 2 \n" "1 3 4 \n" "2 3 1 \n" "2 4 4 \n" "2 5 2 \n" "3 5 3 \n" "4 6 2 \n" "5 4 3 \n" "5 6 2 \n" " \n" "5 7 \n" "1 2 10 \n" "1 4 30 \n" "1 5 100\n" "2 3 50 \n" "3 5 10 \n" "4 3 20 \n" "4 5 60 \n" ); Graph G(in), H(in); G.write( cout ); cout << "\n\n"; H.write( cout ); }``````

 ``` 0 2 4 0 0 0 0 0 1 4 2 0 0 0 0 0 3 0 0 0 0 0 0 2 0 0 0 3 0 2 0 0 0 0 0 0 0 10 0 30 100 0 0 50 0 0 0 0 0 0 10 0 0 20 0 60 0 0 0 0 0 ```
Topic archived. No new replies allowed.