6 Write a C program called adjmatrixcpp that converts a dire

6. Write a C++ program called adj_matrix.cpp that converts a directed graph stored in an input file into an adjacency matrix format. Your program should get an input file name from a user first. Then, it should read the content of the file and display the graph in the adjacency matrix format. In the assignment, you can assume that the maximum number of vertices in the input graph is less than or equal to 50.

Input file format: This is a sample input file called t1.txt.

For the homework, you MUST assume that a whitespace (=blank space, return key, etc.) is used as a delimiter. If your program does not read the file properly, your program will get no credit.

The following presents a sample execution of the C++ program. Your program should run exactly like this.

12 3201

Solution

#include <iostream>
#include <fstream>
using namespace std;

int main () {
string line;
int vertices;
int edges;
cout<< \"Enter input file name: \";
string filename;
cin>>filename;
ifstream myfile (filename);
if (myfile.is_open())
{
myfile >> vertices;
myfile >> edges;
int matrix[vertices][vertices];
for (int j=0;j<vertices;j++){
for (int k=0;k<vertices;k++){
matrix[j][k]=0;
}
}
for (int i=0; i< edges; i++){
int a,b;
myfile >>a >> b;
matrix[a][b] = 1;
}
cout<< \"Number of vertices: \"<< vertices<< \"\ \";
cout<< \"Number of edges: \"<< edges<< \"\ \";

cout<<\"Adjacency matrix:\ \";
for (int j=0;j<vertices;j++){
cout<<\" \";
for (int k=0;k<vertices;k++){
cout<<matrix[j][k]<<\" \";
}
cout<<\"\ \";
}
myfile.close();
}

else cout << \"Unable to open file\";

return 0;
}

6. Write a C++ program called adj_matrix.cpp that converts a directed graph stored in an input file into an adjacency matrix format. Your program should get an

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site